简体   繁体   English

如何仅使用 fork/exec/pipe/dup2 捕获子进程的标准输出?

[英]How to capture the stdout of a child process using fork/exec/pipe/dup2 only?

so I'm trying to capture the output of a child process using fork/exec/pipe/dup2 only but the output keeps printing to terminal instead.所以我试图仅使用 fork/exec/pipe/dup2 捕获子进程的输出,但输出会继续打印到终端。 This is my code right now:这是我现在的代码:

import os
import sys

pipeIn, pipeOut = os.pipe()
processid = os.fork()
if processid == 0:
    try:
        os.close(pipeIn)
        os.dup2(pipeOut, 0)
        os.execv(sys.executable, [sys.executable, 'helloWorld.py'])
        sys.exit(0)
    except FileNotFoundError:
        print("ERROR: File not found.")
        sys.exit(1)
elif processid == -1:
    print("ERROR: Child was unable to run.")
    sys.exit(1)
else:
    wait = os.wait()
    if wait[1] == 0:
        os.close(pipeOut)
        output = os.read(pipeIn, 100)
    else:
        output = "ERROR"

Can anyone tell me what's going wrong?谁能告诉我出了什么问题? And how I can capture the output of the exec command instead of printing it to terminal.以及如何捕获 exec 命令的输出而不是将其打印到终端。 (No temp files are allowed either). (也不允许使用临时文件)。

Standard output is FD 1, but you're dup 'ing your pipe over FD 0 (standard input) instead.标准输出是 FD 1,但您正在通过 FD 0(标准输入) dup管道。 Change os.dup2(pipeOut, 0) to os.dup2(pipeOut, 1) .os.dup2(pipeOut, 0)更改为os.dup2(pipeOut, 1)

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

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