How to make child process die after parent exits?

后端 未结 24 1731
天涯浪人
天涯浪人 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:28

    Inspired by another answer here, I came up with the following all-POSIX solution. The general idea is to create an intermediate process between the parent and the child, that has one purpose: Notice when the parent dies, and explicitly kill the child.

    This type of solution is useful when the code in the child can't be modified.

    int p[2];
    pipe(p);
    pid_t child = fork();
    if (child == 0) {
        close(p[1]); // close write end of pipe
        setpgid(0, 0); // prevent ^C in parent from stopping this process
        child = fork();
        if (child == 0) {
            close(p[0]); // close read end of pipe (don't need it here)
            exec(...child process here...);
            exit(1);
        }
        read(p[0], 1); // returns when parent exits for any reason
        kill(child, 9);
        exit(1);
    }
    

    There are two small caveats with this method:

    • If you deliberately kill the intermediate process, then the child won't be killed when the parent dies.
    • If the child exits before the parent, then the intermediate process will try to kill the original child pid, which could now refer to a different process. (This could be fixed with more code in the intermediate process.)

    As an aside, the actual code I'm using is in Python. Here it is for completeness:

    def run(*args):
        (r, w) = os.pipe()
        child = os.fork()
        if child == 0:
            os.close(w)
            os.setpgid(0, 0)
            child = os.fork()
            if child == 0:
                os.close(r)
                os.execl(args[0], *args)
                os._exit(1)
            os.read(r, 1)
            os.kill(child, 9)
            os._exit(1)
        os.close(r)
    

提交回复
热议问题