3

I have some time consuming task in a function and i want this function to run even after the main process exited.

Code sample:

def do_time_consuming_thing():
    // do time consuming task here
    time.sleep(30)

def worker():
    print "start a child process:"
    p = multiprocessing.Process(target=do_time_consuming_thing,args=())
    p.start()
    print "child pid:%d" % p.pid
    sys.exit(0) // main process exit here.

def test():
    worker()

But when i run the above code in shell command line, i can not return to the command line prompt before the child process finishes.

How can i return to the command line prompt immediately after the sys.exit(0) finishes.

Ke Lu
  • 129
  • 3
  • 16
  • I can use os.fork() to achieve this, but i want to know whether there is a way multiprocessing can do it. – Ke Lu Aug 04 '17 at 02:34

2 Answers2

3

In your code replace your exit line

sys.exit(0)

with this:

os._exit(0)

From the python docs:

os._exit(n)

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

I can't say I recommend this approach, but it answers your question if the requirement is to use the multiprocessing module.

Michael Guffre
  • 349
  • 1
  • 3
1

Try setting p.daemon = True before p.start(). See here.

xyzzy
  • 70
  • 7
  • It does not work. The child process will terminate immediately after the sys.exit(0) called, as the main process is the only non-daemon process. – Ke Lu Aug 04 '17 at 02:40
  • 1
    Oh, you want your code to execute in the background and return to the shell while it's executing? Try running `python script.py &` on Linux or osx. I'm not sure how to do it on windows. – xyzzy Aug 04 '17 at 02:41
  • No, i can not use the script in this way. – Ke Lu Aug 04 '17 at 02:42
  • Take a look at this thread: https://stackoverflow.com/q/24694763/3573344 – xyzzy Aug 04 '17 at 02:46