无法从子进程写入文件

时间:2018-02-28 11:44:39

标签: python

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

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永远不会打印出来。

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

谢谢!

1 个答案:

答案 0 :(得分: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。因此,考虑到您的代码,问题不在于可以复制的部分。

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

pickle.dump(proc.pid,p) # write to file
pickle.load(open(s, "rb")) #read from file