简体   繁体   English

无法从子进程写入文件

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

I can't wrap my head around this... I have the following code: 我无法解决这个问题...我有以下代码:

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())

Here's the output: 这是输出:

  • $pid $ pid
  • TimeoutError occurred 发生TimeoutError

The script seem to be hanging at opening pf for writing. 该脚本似乎在打开pf进行写作时挂了。 I verified, the file if not created, Hello World never gets printed. 我验证了该文件(如果未创建),则从不打印Hello World。

Why is this happening, and how can fix it? 为什么会发生这种情况,如何解决呢?

Thanks! 谢谢!

I have reduced your code to this (removing everything I could not reproduce given your code): 我已将您的代码简化为此代码(删除了您的代码无法复制的所有内容):

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())

However, it works just fine, it prints Read from file: 12075 . 但是,它工作得很好,它会打印Read from file: 12075 So the issue is not in the part that can be reproduced, given your code. 因此,考虑到您的代码,问题不在可以复制的部分中。

To read/write the procid to the binary file I succesfully used the pickle module: 要将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