How to make child process die after parent exits?

后端 未结 24 1729
天涯浪人
天涯浪人 2020-11-22 05:31

Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure o

24条回答
  •  无人及你
    2020-11-22 06:18

    If you're unable to modify the child process, you can try something like the following:

    int pipes[2];
    pipe(pipes)
    if (fork() == 0) {
        close(pipes[1]); /* Close the writer end in the child*/
        dup2(0, pipes[0]); /* Use reader end as stdin */
        exec("sh -c 'set -o monitor; child_process & read dummy; kill %1'")
    }
    
    close(pipes[0]); /* Close the reader end in the parent */
    

    This runs the child from within a shell process with job control enabled. The child process is spawned in the background. The shell waits for a newline (or an EOF) then kills the child.

    When the parent dies--no matter what the reason--it will close its end of the pipe. The child shell will get an EOF from the read and proceed to kill the backgrounded child process.

提交回复
热议问题