1

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) 
4
  • Look into the subprocess module. Commented Jan 24, 2013 at 6:35
  • 1
    @JoachimPileborg : subprocess is good but not what I want, since I want to limit resource in the child process. Commented Jan 24, 2013 at 6:37
  • 2
    Looks like this is what you want: stackoverflow.com/a/8500169/10601 Commented Jan 24, 2013 at 6: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. Commented Jan 24, 2013 at 14:01

1 Answer 1

4

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) 

```

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.