Reputation: 6018
I seem to have a vague memory that some facility in Linux exists that allows one to fork() a process in such a way that the child is automatically reaped by the system without a zombie being created. What is this mechanism? Or is my memory just wrong?
Upvotes: 3
Views: 493
Reputation: 404
This can also be done via prctl()
prctl(PR_SET_PDEATHSIG, SIGTERM);
The above line inserted in the child process can cause it's termination when the parent process is dead. This can also work when any sub-reapers die(after they parent the child process), and if you need it's actual parent's death to kill the child process, then store the parent's pid
before fork()
and check it in the child process.
if (getppid() != parent_pid_before_fork)
exit(1);
Upvotes: 0
Reputation: 26757
You can ignore SIGCHLD so it's doesn't create zombie ;)
signal(SIGCHLD, SIG_IGN);
doc here: http://man7.org/linux/man-pages/man2/sigaction.2.html
Upvotes: 2
Reputation: 6018
I was thinking of Glib's g_spawn_* methods that auto-reap the child unless you specify you don't want that default behavior.
Upvotes: 3
Reputation: 215437
The portable way to do this is to double-fork:
pid = fork();
if (pid>0) {
int status;
while (waitpid(pid, &status, 0) && !WIFEXITED(status) && !WIFSIGNALED(status));
if (WIFSIGNALED(status) || WEXITSTATUS(status)) goto error;
} else if (!pid) {
pid = fork();
if (pid) _exit(pid<0);
else {
// do child work here
_exit(0);
}
} else goto error;
Upvotes: 4