Execute a C program and retrieve information

Hi
I have the following script:
#!/bin/sh
gcc -o program program.c
./program &
PID=$!

where i execute a C program and i get its pid. I want to retrieve information about this program (e.g memory consumption) using command top.
So far i have: top -d 1.0 -p $PID
But i dont know how to stop top. Commands after 'top' never execute.

You may be better using ps Depending on your flavour & version of operating system, ps can have many variations, for instance some operating systems allow you to:

ps -lp $pid

The memory usage (size) is about the 9th or 10th field.

If I have missed the point, do write back and we'll see if someone can answer.

Robin
Liverpool/Blackburn
UK

Thanks for your reply,
I want to retrieve information for the process every 1 sec and i am not sure if tha's possible with ps, also the script is for a project where i am asked to use top. So i need to use top :slight_smile:

Well a simple loop should suffice. Following your code:-

flag=0
while [ $flag -eq 0 ]
do
   ps -lp $PID | grep -v PID
   flag=$?
   sleep 1
done

The grep -v PID removes the headings. You can either count your way along to the correct field, or have a look at man ps and decide which fields you want and just output them with the -o flag, e.g.

   ps -p $pid -o vsz=             # No grep -v PID bit required

should give you the vitual memory size without headings for the process specified.

I hope that this helps, but do write back if it does not. :slight_smile:

Robin
Liverpool/Blackburn
UK

1 Like

Hi
That seems to work great and that's what i want to do but as i said in a previous reply i need to use command top.

There is much variation in "top" "ps" etc.. .

Not clear what Operating System you have or what information you require.
Assuming you are on some sort of Linux I would expect the syntax to be:

top -d 1 -p $PID

As others suggest, "ps" is probably better.

I am on ubuntu 10.10 and i want to know the memory consumption of my program (program.c). I understand that ps is the best choice and i made it work ( #4 reply) but i wonder if it is possible to use command top to do the same thing.