无法从子进程写入文件

问题描述 投票:0回答:1

我无法绕过这个...我有以下代码:

def launch(command):
    pf = os.path.join(working_directory, '.pid')

    pid = os.fork()
    if pid == 0:
        stdout = os.open(..., os.O_WRONLY | os.O_CREAT)
        try:
            proc = Popen(command, shell=False, stdout=stdout, cwd=workdir)
            print(proc.pid)
            with open(pf, 'wb') as p: # pf should not be open as the file is just created.
                p.write(proc.pid)
            print("Hello World")
        except OSError as proc_error:
            ...
        finally:
            os._exit(o) # socketserver catches SystemExit exception (flask)
    else:
        start = time.time()
        while not os.path.isfile(pf): # I'm just checking if that file exists here never opened it in the first place.
            if time.time() - start >= 30:
                 raise TimeoutError...
            time.sleep(5)

        pid = int(open(pf, 'rb').read())

这是输出:

  • $ PID
  • 发生了超时错误

这个剧本似乎挂在开场写作上。我验证了,如果没有创建文件,Hello World永远不会打印出来。

为什么会发生这种情况,如何解决?

谢谢!

python
1个回答
0
投票

我已将代码缩减到此(删除了我无法重现的所有代码):

import os
import time
s = "foo"
pid = os.fork()
from subprocess import Popen

if pid == 0:
    proc = Popen(["sleep", "3"])
    with open(s, "w") as p:
        p.write(str(proc.pid)) # <- Only real error I could see
    os._exit(0)

else:
    start = time.time()
    while not os.path.isfile(s):
        if time.time() - start >= 30:
            raise TimeoutError("Command took to long")
        time.sleep(5)

    print("Read from file: " + open(s, 'r').read())

然而,它工作得很好,它打印Read from file: 12075。因此,考虑到您的代码,问题不在于可以复制的部分。

要读取/写入继续到二进制文件,我成功使用了pickle模块:

pickle.dump(proc.pid,p) # write to file
pickle.load(open(s, "rb")) #read from file
© www.soinside.com 2019 - 2024. All rights reserved.