简体   繁体   English

python分叉的进程未使用os.execlp执行

[英]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. 我已经有了这个简单的python脚本,该脚本应该派生新进程,然后让每个进程都使用os.execlp执行命令,但是执行仅发生一次。 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. 为此,OS X中的“ open -n -a Appname”命令将启动指定应用程序的新实例,因此上面的代码应将分支的进程替换为“ open”命令,并且该命令应运行5次。 However, it only runs once so only one instance of Calculator is opened. 但是,它仅运行一次,因此仅打开了一个Calculator实例。 Despite this, the parent lists 5 child PIDs forked. 尽管如此,父母还是列出了5个分叉的孩子PID。

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; 如果我注释掉os.execlp行并取消注释其后的os.popen和os._exit行,则此操作正常,子进程全部运行“ open”命令; however, I am wondering why the approach of replacing the forked process using execlp (or execvp and other similar variants) is not working? 但是,我想知道为什么使用execlp(或execvp和其他类似变体)替换分叉进程的方法不起作用? Clearly the child process is running, as I can use piping to run the "open" command just fine. 显然子进程正在运行,因为我可以使用管道来运行“ open”命令。

This is with python 3.4.3. 这是python 3.4.3。

The first argument, after the executable, is arg[0] which is by convention the name of the executable. 可执行文件之后的第一个参数是arg [0],按照惯例,它是可执行文件的名称。 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 . 在您的情况下,您将程序命名为'-n' ,而实际参数仅为-aCalculator So you have to repeat 'open' : 所以你必须重复'open'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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