0

我有一个更大的程序(150 行左右),但这似乎是我唯一的问题。我设法减少了这个问题,并将它变成了一个更小的程序。本质上,它分叉程序并尝试执行 linux 命令(我正在使用 ubuntu 运行它)。我得到以下输出:

Current instruction is bin/ls
Current instruction is bin/ls

Child PID is 984
Traceback (most recent call last):
 File "./Test.py", line 17 in <module>
   makeFork("bin/ls")
 File "./Test.py", line 12, in makeFork
   os.execl(instruction, instruction)
 File "/usr/lib/python2.7/os.py", line 314, in execl
   execv(file, args)
OSError: [Errno2] No such file or directory

Parent PID is 4

下面是程序的代码

import os
from time import sleep
os.system("clear")

def makeFork(instruction):
    PID = os.fork() #Creating a fork for the child process
    sleep(2)
    print("Current instruction is " + instruction)
    if PID == 0:
        print("\nChild PID is " + format(os.getpid()))
        os.execl(instruction, instruction)
    sleep(2)
    print("\nParent PID is " + format(os.getppid()))


makeFork("bin/ls")

我哪里错了?

4

1 回答 1

1

bin/lsis not /bin/ls:没有前导的名称/是相对于您当前的工作目录的,因此要求您的当前目录有一个名为bin包含可执行文件的子目录ls

因为不存在这样的目录,所以您会得到一个 errno 2(“没有这样的文件或目录”)。将您的调用更改为:

makeFork("/bin/ls")

...它运行正确。

于 2019-04-01T15:15:38.897 回答