簡體   English   中英

如何僅使用 fork/exec/pipe/dup2 捕獲子進程的標准輸出?

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

所以我試圖僅使用 fork/exec/pipe/dup2 捕獲子進程的輸出,但輸出會繼續打印到終端。 這是我現在的代碼:

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"

誰能告訴我出了什么問題? 以及如何捕獲 exec 命令的輸出而不是將其打印到終端。 (也不允許使用臨時文件)。

標准輸出是 FD 1,但您正在通過 FD 0(標准輸入) dup管道。 os.dup2(pipeOut, 0)更改為os.dup2(pipeOut, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM