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.
Asked
Active
Viewed 1,005 times
-2
-
2The [source code](http://www.unixtop.org/) for `top` perhaps? – tangrs Jun 17 '14 at 08:52
-
how do i get the source code for top? – Ind Jun 17 '14 at 09:09
1 Answers
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
-
how to create a simple interface in procfs for calculating running time of process – Ind Jun 18 '14 at 06:12
-
Did you *carefully* read [proc(5)](http://man7.org/linux/man-pages/man5/proc.5.html)? The answer is *there* – Basile Starynkevitch Jun 18 '14 at 06:51
-
-
No, AFAIK. And other ways probably go thru `/proc`. Did you understand what `/proc/self/status` (and `/proc/self/stat`) and `/proc/1234/status` is giving? – Basile Starynkevitch Jun 18 '14 at 08:03
-
-
I improved my answer, but the mere fact that you asked shows that you did not read *carefully enough* the man page of `proc(5)` – Basile Starynkevitch Jun 18 '14 at 08:36