Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get stdout of already running process in Linux in C

Tags:

c

linux

Right now, I'm having to start an external process in C. I'm currently using posix_spawn to create the process. It is necessary that I can monitor whether or not the process has terminated. I need to also have a link to the standard out of the process. I've looked at using popen, however, it does not provide an "easy" way of getting the pid. I'm slowly going insane as it can't possibly be this hard to get the stdout of a running process in Linux.

Also, on a further note, I need help deciphering what the file_actions parameter is supposed to mean. man(3) for posix_spawn on this topic says:

If file_actions is not NULL, then the file descriptors open in the child process shall be those open in the calling process as modified by the spawn file actions object pointed to by file_actions and the FD_CLOEXEC flag of each remaining open file descriptor after the spawn file actions have been processed.

If that isn't the definition of a run-on sentence, I have no idea what is.

like image 695
alekpr Avatar asked Feb 05 '14 18:02

alekpr


1 Answers

Since you have the PID (returned from posix_spawn) and you are running Linux, you will find the stdout of the process at /proc/<pid>/fd/1. Just open (or fopen) the file for reading.

The standard way is to use fork though. Use pipe and dup2 to get a file descriptor for reading the child's output, as in this question.

like image 182
Alexandre C. Avatar answered Sep 22 '22 15:09

Alexandre C.