Reputation: 772
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
Upvotes: 6
Views: 2456
Reputation: 6193
I think when you fork() a process in C, you can't pass any descriptor from child process back to parent - but may be I'm wrong. Only what you get is PID of new child process. The best way should be you open a pipe (with conventionally name, eg. pipe name contains the PID of process), and then you can open that from anywhere.
Finally, when you fork() the process, it gives to you the PID, and you can write both PID (C binary and forked) to stdout of C program, example with a separator:
cpid = fork();
printf("%d|%d", (int)get_pid(), cpid);
Good luck :)
Upvotes: 0
Reputation: 28489
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.
Upvotes: 1