Tuesday, March 11, 2008

[Programming] Processes (2) - Zombie processes

Last time we mentioned that we can use fork() to create child processes. However, you should keep this in mind: the child process is schedulued independently of the parent process. It implies that you cannot predict which process will execute before or after another, namely, the order of the occurrence of multi processes cannot be forecast. This situation also occurs in multi-threaded programming.

Therefore, some advanced, even sophisticated mechanisms must be used in mutlitasking programming to control the programs running in the desired order.

For example, in some cases you may want the parent process to wait until its child processes have completed. This can be done using the wait family functions, such as wait(), waitpid(), wait3() etc.

However, we need to pay attention to the occurrence of "Zombie" processes. When a child process terminates, its association (such as exit status) with its parent does not vanish immediately, it is still in the system. In this case, this terminated child process becomes a "Zombie" process. It is the responsibility of the parent process to clean up the zombie child processes. The wait() function we mentioned above can do this clean up work.

If you have too many zombie processes in the system, you may suffer slower performance since they consume resources. So you need to avoid zombie processes. Fortunately, when the parent process exits, a special process called init() with process ID of 1 will do the clean up work automatically for you.

You may ask why we don't notify the parent process when a child terminates. Great, you make it! In Linux, child process can send signals to parent when it terminates. We'll touch it in the next post.

No comments: