The /proc pseudo-filesystem
The kernel’s process table, and the state of the processes in it, are available in the /proc pseudo-filesystem, identified by their PIDs. If you want information about PID 28741, then /proc/28741/ contains the relevant information. There is also a special symbolic link, called /proc/self: To any process that refers to /proc/self, it will appear as a symbolic link to the running process. This is not always easy to spot:
$ echo $$ 2168 $ ls -ld /proc/self /proc/$$ dr-xr-xr-x 7 steve steve 0 Nov 12 16:06 /proc/2168 lrwxrwxrwx 1 root root 64 Nov 12 15:56 /proc/self -> 2171
What is happening here is not necessarily intuitive. The shell has a PID of 2168, and the shell passes the value of $$ to ls. In the ls program, /proc/self is /proc/2171 because ls is running as PID 2171. So these two are not the same number.
This script uses the /proc virtual filesystem to get the state of a given process along with the CPU that it was most recently run on. This can be useful for correlating with what top says about I/O Wait states, for example. Of course, you can use it to display almost anything about the process; in the Linux kernel source, /fs/proc/array.c contains the do_task_stat() function, which is what writes /proc/<pid>/stat.
$ cat stat.sh #!/bin/sh # Example on RHEL5 (2.6.18 kernel): #23267 (bash) S 23265 23267 23267 34818 23541 4202496 3005 27576 1 6 4 3 45 16 15 0 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access