popen
on Unix is done using fork
. That means you’ll be safe with:
- you run
Popen
in your parent process - immediately exit the parent process
When the parent process exits, the child process is inherited by the init
process (launchd
on OSX) and will still run in the background.
The first two lines of your python program are not needed, this perfectly works:
import subprocess
p = subprocess.Popen(['nc', '-l', '8888'],
cwd="https://stackoverflow.com/",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
I was reading about double-forks and not sure if this is necessary
This would be needed if your parent process keeps running and you need to protect your children from dying with the parent. This answer shows how this can be done.
How the double-fork works:
- create a child via
os.fork()
- in this child call
Popen()
which launches the long running process - exit child:
Popen
process is inherited byinit
and runs in the background
Why the parent has to immediately exit? What happens if it doesn’t exit immediately?
If you leave the parent running and the user stops the process e.g. via ctrl-C
(SIGINT
) or ctrl-\
(SIGQUIT
) then it would kill both the parent process and the Popen
process.
What if it exits one second after forking?
Then, during this 1s period your Popen
process is vulnerable to ctrl-c etc. If you need to be 100% sure then use the double forking.