Detect death of parent process

前端 未结 3 1524
梦如初夏
梦如初夏 2021-01-04 11:06

How can I detect parent process death in Linux OS?

If in parent process called fork(), that create child process. In the parent process I can use system

3条回答
  •  借酒劲吻你
    2021-01-04 11:30

    If both the parent and child process are under your control for their lifetime, the most portable method is to share one half of a pipe or socket with the parent.

    1. Prior to fork, open a pipe() or socketpair().
    2. After fork,
      1. in the parent, close the read end of the pipe, or the first socket.
      2. in the child, close the write end of the pipe, or the second socket.
    3. In the parent, stash the remaining file descriptor away and forget about it.
    4. In the child, use any of the multiplexed IO methods (select, poll, etc.) to test the descriptor for readability
    5. If the descriptor becomes readable, the parent is almost certainly dead, or some rare bug caused a stray write, which you can check for by calling read(). If the parent really was dead, read() will return 0 bytes.

    The advantage of this method is that it completely avoids signals, which are one of the hardest to master mechanisms in UNIX, and provides a waitable descriptor that can easily be integrated with a network multiplexer or GUI event loop.

提交回复
热议问题