将父进程替换为死后的子进程

时间:2016-05-06 04:19:41

标签: c linux signals

我的目标是制作一个包含父子进程的程序,当任何一个程序被杀死时,它们都会被替换。我正在努力解决的问题是父母去世的情况。在这种情况下,孩子必须升级成为新的父级,然后fork()自己的子级。当我向父进程发送SIGKILL时,我的整个程序似乎突然结束,由于我无法处理SIGKILL,我不确定如何正确地执行此操作。

有没有办法让孩子继续运行才能成为新的父进程?

由于

1 个答案:

答案 0 :(得分:2)

通常情况下,除非您执行以下操作:How to make child process die after parent exits?

,否则您的父母被杀后不应该被杀死。

如果父母被杀,孩子们就会成为初始过程的孩子。您可能在终端上看到,在将KILL发送给父级后,该进程会立即返回。这是因为sub-bash只在父父的PID上等待。但孩子实际上在其他地方跑步。

以下是展示它的示例:

#!/usr/bin/env python
# test_parent_child_kill.py
import os
import time

def child():
    print "Child process with PID= %d"%os.getpid()
    time.sleep(20)

def parent():
    print "Parent process with PID= %d"%os.getpid()
    newRef=os.fork()
    if newRef==0:
        child()
    else:
        print "Parent process and our child process has PID= %d"%newRef
        time.sleep(20)

parent()

然后在睡眠期间:

user@mac:/tmp|⇒  python test_parent_child_kill.py
Parent process with PID= 17430
Parent process and our child process has PID= 17431
Child process with PID= 17431

user@mac:/tmp|⇒  kill 17430

user@mac:/tmp|⇒  ps -ef | grep 17431
503 17431     1   0  9:30PM ttys000    0:00.00 /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python test_parent_child_kill.py

所以孩子还活着。

- 编辑 -

  1. 为什么当父母被杀时我的程序会退回到shell?
  2. Bash也通过folk / exec通过类似的方式调用命令:

    childPid = fork();
    if (childPid == 0){
        executeCommand(cmd); //calls execvp  
    } else {
        if (isBackgroundJob(cmd)){
            record in list of background jobs
        } else {
            waitpid (childPid);
        }       
    }
    

    从bash的角度来看,你的程序的父级是子级,当它从waitpid(childPid)返回时会返回提示输入。

    1. 有没有办法留在程序中并继续按原样运行,但是有了新的父母?
    2. 如果您想要重新附加"可能会有点困难,但这并非不可能:

      Attach to a processes output for viewing

      https://unix.stackexchange.com/questions/58550/how-to-view-the-output-of-a-running-process-in-another-bash-session

      参考:

      http://www.cs.cornell.edu/Courses/cs414/2004su/homework/shell/shell.html

相关问题