简体   繁体   中英

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. 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. (No temp files are allowed either).

Standard output is FD 1, but you're dup 'ing your pipe over FD 0 (standard input) instead. Change os.dup2(pipeOut, 0) to os.dup2(pipeOut, 1) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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