简体   繁体   中英

python forked processes not executing with os.execlp

I've got this simple python script that ought to fork new processes and then have each execute a command using os.execlp, but the execution only occurs once. I'm curious if there's a timing issue going on that is preventing the additional forks from executing:

import os

for n in range(5):
    PID = os.fork()
    if PID == 0: #the child...
        print("This child's PID is: %s" % os.getpid())
        os.execlp('open','-n','-a','Calculator')
        # os.popen('open -n -a Calculator')
        # os._exit(0)
    else:
        print("new child forked: %d" % PID)

For this, the "open -n -a Appname" command in OS X launches a new instance of the specified application, so the above code should replace the forked process with the "open" command, and this should run 5 times. However, it only runs once so only one instance of Calculator is opened. Despite this, the parent lists 5 child PIDs forked.

If I comment out the os.execlp line and uncomment the os.popen and os._exit lines following it, then this works properly and the child processes all run the "open" command; however, I am wondering why the approach of replacing the forked process using execlp (or execvp and other similar variants) is not working? Clearly the child process is running, as I can use piping to run the "open" command just fine.

This is with python 3.4.3.

The first argument, after the executable, is arg[0] which is by convention the name of the executable. This is useful, if you have symbolic links, which determine the behavior of the programm. In your case, you name the programm '-n' and the real arguments are only -a and Calculator . So you have to repeat 'open' :

os.execlp('open', 'open', '-n', '-a', 'Calculator')

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