I have a question regarding Linux in general, though an answer for Bash would be optimal. How would one read the stdin/stdout/stderr of a given process (by PID) from a script? In other words, how can I get the stdin/stdout/stderr of another program from a script? I have as yet been unable to find any answers online elsewhere.
So far, I have been able to find the process id
pidof {some-process-name}
And then find the location of its stdin socket (I think that's what it's called...)
readlink -f /proc/{PID}/fd/0
Which usually produces something like
/dev/pts/1
Then I am able to write to that stdin
echo "Hello World" > /dev/pts/1
However attempting to read from either that socket
cat /dev/pts/1
Or from the original file
cat /proc/{PID}/fd/0
Both produce nothing, simply waiting indefinitely, even after the process is terminated, and thus the file deleted.
Any help would be much appreciated. Thank you in advance!
UPDATE: Found a way to solve the problem, see my answer below.
You cannot interact with a program's file descriptors after it has been started. The entries in /proc/$pid/fd/
simply tell you where the file descriptors are connected -- you can write to the place which is connected to stdout, and find out where it's reading its stdin from, but not change what they are connected to or inject new data into any of those streams.
A common workaround for this is to run the program under a tool which enables these operations (expect
, tmux
, etc) but of course that needs to happen at the time you start the program.