Skip to content
Advertisement

How to wait() only for some child processes and prevent zombies

I’m trying to write a mock-shell in c on linux, and got stuck on this problem:

I need to run some processes in the background, and some processes in the foreground. To prevent the foreground processes from becoming zombies, I can use wait(), but how do I prevent the background processes from becoming zombies?

Advertisement

Answer

You cannot prevent any process from becoming a zombie, but you can limit the time that it remains one. A process is a zombie from the time it terminates to the time its parent collects it via a call to wait() or waitpid() or another function serving that purpose. That time can be made very short indeed, for instance if the parent process is already waiting when the child terminates, but termination and subsequent collection are not synchronous.

The distinction between background and foreground processes is primarily about control of a terminal; it has little to do with a parent shell managing child processes. You collect child processes belonging to background jobs via wait(), etc., exactly the same way you collect child processes belonging to foreground jobs. You can can collect already-terminated children without waiting for unterminated ones by using waitpid() with the W_NOHANG flag, as @Someprogrammerdude already described. It remains to insert such waits at an appropriate time, and it seems common for interactive shells to schedule that around reading commands from the user.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement