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

后端 未结 2 1775
孤独总比滥情好
孤独总比滥情好 2020-11-30 04:05

I\'m seeking for ways to write data to the existing process\'s STDIN from external processes, and found similar question How do you stream data into the STDIN

相关标签:
2条回答
  • 2020-11-30 04:34

    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 too
    echo "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.

    0 讨论(0)
  • 2020-11-30 04:47

    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/python
    
    import os, sys
    if __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

    0 讨论(0)
提交回复
热议问题