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
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.
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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With