Get stdout / stderr of a forked process in a subprocess

I have a C program that calls fork()

And I have a python script that executes a C program using

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

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

Sincerely, many thanks :)

Fabian

+6
source share
2 answers

What you ask for will be complex and will not be possible in pure python - you will need some OS-specific mechanisms.

You really ask for two things:

  • Define a forked process from the PID of the parent process
  • Intercept standard to / from arbitrary process

Perhaps you could do the former by analyzing / proc, if you were on Linux, the latter is really a functional function of the debugger (for example, How can I intercept the stdout and stderr process of another process on Linux? )

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

+1
source

I think that when you do fork () in C, you cannot pass any handle from the child process back to the parent, but maybe I'm wrong. Only what you get is the PID of the new child process. The best way is to open a channel (with a conditional name, for example, the channel name contains the PID of the process), and then you can open it from anywhere.

Finally, when you execute the fork () process, it gives you the PID, and you can write both the PID (C binary and forked) in the stdout of the C program, for example with a separator:

 cpid = fork(); printf("%d|%d", (int)get_pid(), cpid); 

Good luck :)

0
source

Source: https://habr.com/ru/post/909392/


All Articles