Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why python script hangs after the main process exited

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.

like image 344
Ke Lu Avatar asked Oct 19 '25 05:10

Ke Lu


2 Answers

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.

like image 167
Michael Guffre Avatar answered Oct 21 '25 20:10

Michael Guffre


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

like image 23
xyzzy Avatar answered Oct 21 '25 20:10

xyzzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!