2

I want to run a program in another process, get pid this program and child process should be not depended from parent. Please see following Python code:

cmd = 'myPythonProgramm -p param'
pid = subprocess.Popen(cmd, shell = True).pid

But if I kill parent process then also kill child process.
This issue is not exist if I use:

os.system('nohup myPythonProgramm -p param &')

But in this case I can't get child process pid.
How can I run a program in another process, get pid this program and child process should be not depended from parent?

Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45

1 Answers1

3

You are running into Unix process group management. In particular, when you kill the session leader of a process group when it is attached to a terminal (as is your script), all processes in that group receive a SIGHUP, which by default causes termination.

One solution is to establish a new session for the child using os.setsid(). In Python 3 subprocess.Popen() accepts a start_new_session=True which does this for you. For Python 2, we can get a similar solution using preexec_fn:

subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
dhke
  • 15,008
  • 2
  • 39
  • 56