4

I know pgrep, top, and ps all query /proc filesystems. So far so good. Yet what got me thinking is that in the past there was no /proc filesystem. Even nowadays, Mac OS X, as far as I know, has no /proc filesystem, yet top still accesses process info, which sugggests to me such info should be coming from kernel directly. My question, however, is specific to Linux. Which libraries and/or syscalls can be used to query process information directly, bypassing /proc ?

4

It is possible to query process information from the Linux kernel directly — by reading files under /proc. This is the way it's done on Linux, Solaris and several other Unix variants.

Ancient Unix systems had a ps command that was setuid root and mapped some kernel memory (through /dev/kmem or similar) and parsed kernel data structures. This required ps to have privileges (dangerous) and to be tied to the exact kernel version (inconvenient).

On modern *BSD systems, ps works by calling the sysctl function, which in turn makes system calls to retrieve information formatted as structures defined by a binary format. MacOS uses the same mechanism.

Linux does not have this BSD interface. It uses procfs and sysfs to allow userland to retrieve information from the kernel. Where BSD marshals information in a binary format retrieved by a special-purpose system call, Linux marshals information as strings retrieved through ordinary file access to a special-purpose filesystem. It would be possible to use the same method as in ancient Unix systems, but nobody does it because it's such an inferior method (requires privileges and requires updating whenever the kernel data structures change).

  • In general, BSD sysctl actually does not incorporate multiple processes, or even a single process, mapping any areas of shared memory. Rather, it is just several thousand get/set system calls all rolled into one. Specifically, the FreeBSD sysctl for CTL_KERN-KERN_PROC involves no memory mapping. – JdeBP Jan 29 '17 at 9:17
  • @JdeBP Oh, thank you. I thought that sysctl used KVM. It's documented as a libc function, not as a system call. So it's a system call on all *BSD then, marshalling a binary structure into the caller's memory? – Gilles Jan 29 '17 at 16:05
  • The package that provides ps is called procps because it was an alternative, coexisting for a time with the older package called kmem-ps. – user41515 Jan 29 '17 at 16:58
3

Before the advent of the /proc filesystem, psutils read the information directly via /dev/kmem, the kernel memory pseudo device. Obviously only certain versions of ps worked with any given kernel version, which was one argument in favor of /proc. (Being human readable, and easier access to kernel structures for things like perl scripts are arguably bigger benefits.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.