Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the stdout/stderr of a forked process in a subprocess

I have a C program which calls fork()

And I have a python script which executes the C program with

child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE,stdout=subprocess.PIPE, bufsize=0)

Now I can read from stdout and stderr with child.stderr.read(1) or child.communicate(), ... But my problem is now, how can I get only the output from the forked process. Is this even possible? Can I get the pid from both, the original C program and the fork?

kind regards, thank you very much :)

Fabian

like image 278
samuirai Avatar asked Feb 26 '12 13:02

samuirai


People also ask

How do you get stdout and stderr from subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

What does Popen return Python?

The popen() function executes the command specified by the string command. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.

How do I use OS Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.

What does stdout subprocess PIPE mean?

stdout=PIPE means that subprocess' stdout is redirected to a pipe that you should read e.g., using process.communicate() to read all at once or using process.stdout object to read via a file/iterator interfaces.


1 Answers

What you're asking for is going to be complicated and will not be possible in pure python -- you would need some OS-specific mechanisms.

You're really asking for two things:

  • Identify a forked process from the PID of the parent process
  • Intercept the standard in/out of an arbitrary process

You could probably do the former by parsing /proc if you were on Linux, the latter is really a debugger-like piece of functionality (e.g. How can a process intercept stdout and stderr of another process on Linux?)

More likely, you will want to change the way your C program works -- for example, doing the fork()/daemonization from the python script instead of intermediate C code would let you get the child process directly.

like image 183
kdt Avatar answered Oct 03 '22 06:10

kdt