Darwin: how to kill parent process without killing child?
On OS X 10.4/5/6:
I have a parent process which spawns a child. I want to kill the parent without killing the child. Is it poss开发者_Go百科ible? I can modify source on either app.
As NSD asked, it really depends on how it is spawned. If you are using a shell script, for example, you can use the nohup
command to run the child through.
If you are using fork/exec
, then it is a little more complicated, but no too much so.
From 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()
This is one of the best books ever written. It covers these topics in great and extensive detail.
Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series) (Paperback)
ISBN-10: 0321525949
ISBN-13: 978-0321525949
5 star amazon reviews (I'd give it 6).
If the parent is a shell, and you want to launch a long running process then logout, consider nohup (1)
or disown
.
If you control the coding of the child, you can trap SIGHUP and handling it in some non-default way (like ignoring it outright). Read the signal (3)
and sigaction (2)
man pages for help with this. Either way there are several existing questions on StackOverflow with good help.
精彩评论