1

在 OS X 10.4/5/6 上:

我有一个产生孩子的父进程。我想杀死父母而不杀死孩子。是否可以?我可以在任一应用程序上修改源代码。

4

2 回答 2

5

正如 NSD 所要求的,这实际上取决于它是如何产生的。例如,如果您使用的是 shell 脚本,则可以使用该nohup命令运行子程序。

如果您使用的是fork/exec,那么它会稍微复杂一些,但不会太多。

来自http://code.activestate.com/recipes/66012/

import sys, os 

def main():
    """ A demo daemon main routine, write a datestamp to 
        /tmp/daemon-log every 10 seconds.
    """
    import time

    f = open("/tmp/daemon-log", "w") 
    while 1: 
        f.write('%s\n' % time.ctime(time.time())) 
        f.flush() 
        time.sleep(10) 


if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit first parent
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/") 
    os.setsid() 
    os.umask(0) 

    # do second fork
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit from second parent, print eventual PID before
            print "Daemon PID %d" % pid 
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1) 

    # start the daemon main loop
    main() 

这是有史以来最好的书之一。它非常详细地涵盖了这些主题。

UNIX 环境中的高级编程,第二版(Addison-Wesley 专业计算系列)(平装本)

ISBN-10:0321525949
ISBN-13:978-0321525949

5 星亚马逊评论(我会给它 6)。

于 2009-12-23T01:22:10.133 回答
3

如果父级是一个 shell,并且你想启动一个长时间运行的进程,那么注销,考虑nohup (1)or disown

如果您控制孩子的编码,则可以捕获 SIGHUP 并以某种非默认方式处理它(例如完全忽略它)。阅读signal (3)sigaction (2)手册页以获得帮助。无论哪种方式,StackOverflow 上都有几个现有的问题,提供了很好的帮助。

于 2009-12-23T01:19:42.500 回答