6

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

2
  • "Is this even possible?" No. "Can I get the pid from both, the original C program and the fork?" No. The C program owns that child. Your process owns the C program. Now. Stop worrying about Linux details and describe your real problem. Why can't your Python program run the same subprocess as the C program?
    – S.Lott
    Commented Feb 26, 2012 at 15:00
  • an easier way might be using different format of output, the main process could start with: "ParentOutput:", while the output of subprocess is: "ChildOutput:". Then you can just ignore "ParentOutput" in your python program. Commented Feb 26, 2012 at 15:06

2 Answers 2

1

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.

0

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.