Search code examples
clinuxpthreadsfork

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?


Solution

  • 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;