views:

87

answers:

4

I want a script to start a new process, such that the new process continues running after the initial script exits. I expected that I could use multiprocessing.Process to start a new process, and set daemon=True so that the main script may exit while the created process continues running.

But it seems that the second process is silently terminated when the main script exits. Is this expected behavior, or am I doing something wrong?

Edit: Apparently this is expected behavior and I have to use subprocess.Popen() instead. Thanks everyone!

+2  A: 

From the Python docs:

When a process exits, it attempts to terminate all of its daemonic child processes.

This is the expected behavior.

Justin Ardini
Thanks, apparently I didn't RTFM close enough.
JacquesB
+1  A: 

If you are on a unix system, you could use os.fork:

import os
import time

pid=os.fork()
if pid:
    # parent
    while True:
        print("I'm the parent")
        time.sleep(0.5)    
else:
    # child
    while True:
        print("I'm just a child")
        time.sleep(0.5)

Running this creates two processes. You can kill the parent without killing the child.

unutbu
+1  A: 

Here is a related question on SO, where one of the answers gives a nice solution to this problem:

"spawning process from python"

Pontus
+2  A: 

Simply use the subprocess module:

import subprocess
subprocess.Popen(["sleep", "60"])
Philipp