0

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)
Bin Wang
  • 2,697
  • 2
  • 24
  • 34
  • Look into the [`subprocess`](http://docs.python.org/2/library/subprocess.html) module. – Some programmer dude Jan 24 '13 at 06:35
  • 1
    @JoachimPileborg : `subprocess` is good but not what I want, since I want to limit resource in the child process. – Bin Wang Jan 24 '13 at 06:37
  • 2
    Looks like this is what you want: http://stackoverflow.com/a/8500169/10601 – perimosocordiae Jan 24 '13 at 06:50
  • `if pid is 0` is wrong. You must use `if 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 by `os.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. – Celada Jan 24 '13 at 14:01

1 Answers1

3

After os.fork() try this to redirect stdin and stderr:

import os

STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2

# redirect stdout            
new_stdout = os.open(stdout_file, os.O_WRONLY|os.O_CREAT|os.O_TRUNC)
os.dup2(new_stdout, STDOUT_FILENO)

# redirect stderr
new_stderr = os.open(stderr_file, os.O_WRONLY|os.O_CREAT|os.O_TRUNC)
os.dup2(new_stderr, STDERR_FILENO)

```

mib0163
  • 393
  • 3
  • 12