How to write data to existing process's STDIN from external process? How to write data to existing process's STDIN from external process? linux linux

How to write data to existing process's STDIN from external process?


Your code will not work.
/proc/pid/fd/0 is a link to the /dev/pts/6 file.

$ echo 'foobar' > /dev/pts/6
$ echo 'foobar' > /proc/pid/fd/0

Since both the commands write to the terminal. This input goes to terminal and not to the process.

It will work if stdin intially is a pipe.
For example, test.py is :

#!/usr/bin/pythonimport os, sysif __name__ == "__main__":    print("Try commands below")    print("$ echo 'foobar' > /proc/{0}/fd/0".format(os.getpid()))    while True:        print("read :: [" + sys.stdin.readline() + "]")        pass

Run this as:

$ (while [ 1 ]; do sleep 1; done) | python test.py

Now from another terminal write something to /proc/pid/fd/0 and it will come to test.py


I want to leave here an example I found useful. It's a slight modification of the while true trick above that failed intermittently on my machine.

# pipe cat to your long running process( cat ) | ./your_server &server_pid=$!# send an echo to your cat process that will close cat and in my hypothetical case the server tooecho "quit\n" > "/proc/$server_pid/fd/0"

It was helpful to me because for particular reasons I couldn't use mkfifo, which is perfect for this scenario.