How to determine the state of a process (i.e. if it is a zombie)

Tilo Prütz picture Tilo Prütz · Mar 11, 2009 · Viewed 8.3k times · Source

how can I get information on the state of a process (i.e. if it is a zombie) using C under Linux?

After reading the answers so far I want to narrow my question somewhat: I would prefer a pure C solution. After reading the ps source (which reads /proc/) I thought that there should be a better way and asked here :)

Answer

Jason L picture Jason L · Mar 11, 2009

You'll want to learn about interacting with the /proc/ "psuedo-filesystem" via typical C standard library calls. The documentation necessary to get started is included with any Linux distro and is a simple google search away.

(Now that you know what to search for. I know that's usually most of the challenge!)

In short, the directories and files within the /proc/ directory of a running Linux system reflect the state of the running kernel, which (naturally) includes processes. However, before you charge in you need to keep some information in mind.

A zombie process isn't the same thing as an orphaned process. An orphaned process is a process left running in a waiting state after the process' parent has exited incorrectly. A zombie process is a process which has exited properly, released all its resources, but is maintaining a place in the process table.

This typically happens when a process is launched by a program. You see, the kernel won't remove a finished sub-process' entry in the process table until the parent program properly fetches the return status of the sub-process. That makes sense; how else would the parent program know if the subprocess exited improperly?

So all subprocesses are technically zombies for at least a very short time. It's not inherently a bad state for a program to be in.

Indeed, "zombies" are sometimes created intentionally. For example, sometimes a zombie entry is left in place by a program for a while so that further launched processes won't get the same PID as the previously-launched (and now zombie) process.

In other words, if you go SIGCHLDing zombie processes unnecessarily you might create a serious problem for the spawning program. However, if a process has been a zombie for a half hour or more, it's probably a sign of a bug.

Edit: The question changed on me! No, there's no simpler way than how ps does it. If there was, it would have been integrated into ps a long time ago. The /proc files are the be-all-end-all source for information on the kernel's state. :)