-2

I want to understand the implementation of top command in linux ie how it uses the procfs interface for displaying the top running processes.?what sources should i refer.

Ind
  • 11
  • 3

1 Answers1

3

First, read carefully proc(5). Then study code of procps, and, as commented by tangrs, of unixtop, i.e. top-3.7.tar.gz

For example, your program might do

{ FILE* psf = fopen("/proc/self/statm", "r");
  if (psf) { 
     int progsize = 0; 
     fscanf(psf, "%d", &progsize);
     printf ("program size is %d pages\n", progsize);
     fclose(psf);
  } else perror("fopen /proc/self/statm");
}

to print its own program size. You could make it a function:

int get_my_program_size(void) {
  int progsize = -1;
  FILE* psf = fopen("/proc/self/statm", "r");
  if (psf) {  
    fscanf(psf, "%d", &progsize);
    fclose(psf);
  } else perror("get_my_program_size /proc/self/statm");
  return progsize;
}

This is really quick: no disk i/o is involved, since the /proc/ filesystem is a pseudo-filesystem and its file contents are computed on the fly and on demand. These pseudo-files (like /proc/1234/statm or /proc/1234/status etc....) should be read sequentially.

If you want user-mode CPU time, you could parse the 14th field (utime) of /proc/self/stat (or of /proc/1234/stat for the process of pid 1234). I leave that as an exercise to the reader....

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547