简体   繁体   中英

python -c cmd will wait all process finish

Codes:

File: script.py

from multiprocessing import Process


def func():
    async_process()
    print('OK')
    return 123

def func2(args):
    # do a lot of things here
    # ...
    pass

def async_process():
    p = Process(target=func2, args=args)
    p.daemon = False 
    p.start()

When I directly call the func() in Python script, I can get the returned value immediately, this is what I expect.

But, when I call the func() in command line like this:

python -c "from script import func;func()"

The command line will finish executing until the new created process finished itself. This is not I want.

How should I change the program or how should I write the script to ensure:

  1. I can call the func() in command line;

  2. The command line will immediately return the value when the func() is finished, and won't wait for the new created process.

  3. The new created process can keeps running.

That's because the child process created in async_process() is not detached from its parent, hence the parent has to wait for the child to finish before exiting. If you want to create a daemon process in the Unix meaning of the term, you'll have to use the double-fork method to detach the child from its parent and hand over control to the OS' scheduler. This looks to be a decent recipe for creating Unix daemon processes in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM