I'm using python to os.fork a child progress, and use os.execv to execute another program in the child progress. How can I redirect I/O in the child program. I tried this but failed.
import sys, os pid = os.fork() if pid is 0: sys.stdin = open('./test.in') os.execv('/usr/bin/python', ['python', './test.py']) While test.py is:
import sys print(sys.stdin) a = input() print(a)
subprocessmodule.subprocessis good but not what I want, since I want to limit resource in the child process.if pid is 0is wrong. You must useif pid == 0. Your may happen to work in all versions of CPython (so far), but the language does not in any way guarantee that the 0 returned byos.fork()and the 0 against which you are comparing are the same 0 object. In future CPython versions or in other Python implementations like PyPy, they might very well not be the same 0.