How can I get a process usage using glibc ( getrusage() ) functions ?

It is always possible to fetch different information about a process from “/proc/” filesystem. I can point some important files from “/proc” filesystem to get statistics about a process.

/proc/pid/stat
/proc/pid/statm
/proc/pid/status

You can substitute the “pid” of the process in above and get the status of a process.

I can see some of the above files does not have proper tag to understand the information.

So you can use #man 5 proc command for interpreting proc information .

Using “glibc” fuctions can be an another way to fetch the some information.

I just thought of getting information about “context swithes of a process” using “getrusage()” in my fedora 12 system.

Below is a “C” program to get this information on the same binary.

#include stdio.h
#include sys/time.h
#include sys/resource.h
#include string.h
#include sys/types.h
#include unistd.h
#include time.h

int main ()
{

int i=0;
struct rusage proc_usage;
memset( &proc_usage,0, sizeof (struct rusage));

for (i=0; i< 100; i++)
{
getrusage(RUSAGE_SELF, &proc_usage);
printf (“\n My Process Id is : %d”, getpid());
printf (“\n No of voluntary context switches are : %ld”, proc_usage.ru_nvcsw);
printf (“\n No of involuntary context switches are: %ld\n”, proc_usage.ru_nivcsw);

printf (“\n Process User Time: %ld seconds – %ld Micro seconds \n”, proc_usage.ru_utime.tv_sec, proc_usage.ru_utime.tv_usec);
printf (“\n Process System Time: %ld seconds – %ld Micro seconds \n”, proc_usage.ru_stime.tv_sec, proc_usage.ru_stime.tv_usec);
sleep(3);
}
sleep (10);

}

Above program can be extended as you wish 🙂