How to make child process die after parent exits?

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

    If parent dies, PPID of orphans change to 1 - you only need to check your own PPID. In a way, this is polling, mentioned above. here is shell piece for that:

    check_parent () {
          parent=`ps -f|awk '$2=='$PID'{print $3 }'`
          echo "parent:$parent"
          let parent=$parent+0
          if [[ $parent -eq 1 ]]; then
            echo "parent is dead, exiting"
            exit;
          fi
    }
    
    
    PID=$$
    cnt=0
    while [[ 1 = 1 ]]; do
      check_parent
      ... something
    done
    

提交回复
热议问题