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.
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.
Try setting p.daemon = True
before p.start()
. See here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With