How to make child process die after parent exits?

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

    I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions. This is mental masturbation, but works.

    The trick is:

    • process A is started
    • process A creates a pipe P (and never reads from it)
    • process A forks into process B
    • process B creates a new session
    • process B allocates a virtual terminal for that new session
    • process B installs SIGCHLD handler to die when the child exits
    • process B sets a SIGPIPE handler
    • process B forks into process C
    • process C does whatever it needs (e.g. exec()s the unmodified binary or runs whatever logic)
    • process B writes to pipe P (and blocks that way)
    • process A wait()s on process B and exits when it dies

    That way:

    • if process A dies: process B gets a SIGPIPE and dies
    • if process B dies: process A's wait() returns and dies, process C gets a SIGHUP (because when the session leader of a session with a terminal attached dies, all processes in the foreground process group get a SIGHUP)
    • if process C dies: process B gets a SIGCHLD and dies, so process A dies

    Shortcomings:

    • process C can't handle SIGHUP
    • process C will be run in a different session
    • process C can't use session/process group API because it'll break the brittle setup
    • creating a terminal for every such operation is not the best idea ever

提交回复
热议问题