Implement ps command in C

Hello, could anybody explain how the ps command works? I know something about the proc file system. But I'm still not sure about how it exactly works. Like ps without any option will print out the current user's processes, but it never displays my web browsers such as firefox or my LibreOffice while they're open.

I know all the files with numerical names are PIDs, but I don't know how the ps command differentiate them, catargorizing them according the users who fired them. Or where it gets the TTY and cpu time and CMD info.

That would be wonderful if someone could give a simple example about how to mimick the functions of ps command just by reading the proc directory(better in C). Thanks a lot.

The details provided by the /proc filesystem (and even if it exists) varies widely from system to system. On systems where it is present, it reflects data found in the kernel's process table (which also varies considerably from system to system).

man /proc

may provide information about how /proc is implemented on your system.

Unlike many "standard" utilities, the code needed to implement ps is not at all portable. On systems that don't support /proc, ps is frequently a set-UID root process that extracts data directly from the kernel's process table by reading /dev/kmem (another interface that is not available on all systems).

yeah, but I just don't know how to make use of those files to get to know the process information which can be obtained by ps command. Can you give me an example that might work on a typical ubuntu ? Thanks a lot

One of the advantages of using an open source system is that you can learn from the source code. Just download the source for Ubuntu's ps implementation and have a look for yourself at what it's doing.

Regards,
Alister

1 Like