arctic_hen7
arctic_hen7

Reputation: 1574

Bash Read Stdin from Given PID

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.

Upvotes: 1

Views: 1520

Answers (2)

arctic_hen7
arctic_hen7

Reputation: 1574

Ok, after about a day of experimenting, I managed to do it. A read stream works on either /proc/{PID}/fd/0 or whatever that file links to (found with readlink as stated in my question). The readstream yields a result every time something is typed into the stdin of the program. For my tests, it seems to only work for the keyboard, not for keystrokes roughly simulated with echo "Hello World" > /dev/pts/1 Nonetheless, it is sufficient for my purposes. Thank you to all others for pointing me in the right direction!

Upvotes: 1

tripleee
tripleee

Reputation: 189739

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.

Upvotes: 1

Related Questions