繁体   English   中英

无法从子进程写入文件

[英]Can't write to file from child process

我无法解决这个问题...我有以下代码:

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
  • 发生TimeoutError

该脚本似乎在打开pf进行写作时挂了。 我验证了该文件(如果未创建),则从不打印Hello World。

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

谢谢!

我已将您的代码简化为此代码(删除了您的代码无法复制的所有内容):

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

暂无
暂无

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

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