I have a program where I need to attach to stdout/stderr of a given pid (fetched from a file).
How this should be done?Is this even possible?
EDIT 1:
I have a monitor program that starts/stops a server program. However, the monitor can be closed/reopened and should hook to existent server stdout to read errors that are written on stdout (and also some output based on some monitor requests).
EDIT 2:
I built server and monitor so I have sources of both, the problem is that the server “answer” to some monitor requests on the stdout, I don’t want to add another interprocess comunication part
While a process is running, there isn’t a standard Unix way to intercept its output from another process and start capturing it after the target process has been started.
If you are starting these processes yourself, via
execve, you can simply set up a pipe viapipe(2)and redirect its descriptors (viadup2(2)) to the child process’ stdin and stdout. This way the parent will be able to write/read to the child’s stdin/stdout through the pipe.Regarding your question after the edit: this seems like a good fit for a Unix fifo file.
A fifo file (or a named pipe) appears like a file, but is implemented as a pipe under the bonnet.
So just create a fifo file (with the
mkfifo(1)command), start the server application by redirecting its stdin and stdout descriptors to that file (with the<and>operators of the shell), and you’ll be able to read from it anytime.