Chimera
Chimera

Reputation: 6018

How to forking process in a way such that reaping the child isn't neccessary

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

Answers (4)

Chaitanya Tetali
Chaitanya Tetali

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

Stargateur
Stargateur

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

Chimera
Chimera

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

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

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

Related Questions