How to make child process die after parent exits?

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

    I don't believe it's possible to guarantee that using only standard POSIX calls. Like real life, once a child is spawned, it has a life of its own.

    It is possible for the parent process to catch most possible termination events, and attempt to kill the child process at that point, but there's always some that can't be caught.

    For example, no process can catch a SIGKILL. When the kernel handles this signal it will kill the specified process with no notification to that process whatsoever.

    To extend the analogy - the only other standard way of doing it is for the child to commit suicide when it finds that it no longer has a parent.

    There is a Linux-only way of doing it with prctl(2) - see other answers.

提交回复
热议问题