Question

I've been trying desperately to kill a child process from the parent.

I've tried: 1. kill -15 pid

  1. kill -shotgun pid

  2. kill -9 pid

They all resolved in having the child process written as : "defunct" (zombie) when ps -A in linux.

How do I kill the process and force it to be cleaned from the process table. I must have it cleaned because its lack of a record in the process table is how I verify in my code that the process is dead.

Thanks :-)

Was it helpful?

Solution

If you want to collect the child process, you have to ask for its exit code using waitpid. From the manpage:

A child that terminates, but has not been waited for becomes a "zombie". The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes.

Usage is somewhat like:

#include <sys/types.h>
#include <sys/wait.h>

...
waitpid(child_pid, 0, 0);

If you want to return immediately, even if the child has not exited yet:

waitpid(child_pid, 0, WNOHANG);

If you just want to collect all zombie children, without finding information about a specific child, you do:

waitpid(-1, 0, WNOHANG);

You could do that in a loop until waitpid returns with a negative number (i.e. error) and errno indicates ECHILD.

This, by the way, also allows you to actually find out what state the process has, read up on the manpage for further information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top