I've tried running things like this:
subprocess.Popen(['nohup', 'my_command'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'))
This works if the parent script exits gracefully, but if I kill the script (Ctrl-C), all my child processes are killed too. Is there a way to avoid this?
The platforms I care about are OS X and Linux, using Python 2.6 and Python 2.7.
The child process receives the same SIGINT
as your parent process because it's in the same process group. You can put the child in its own process group by calling os.setpgrp()
in the child process. Popen
's preexec_fn
argument is useful here:
subprocess.Popen(['nohup', 'my_command'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'),
preexec_fn=os.setpgrp
)
(preexec_fn
is for un*x-oids only. There appears to be a rough equivalent for Windows "creationflags=CREATE_NEW_PROCESS_GROUP
", but I've never tried it.)