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

后端 未结 2 1851
孤独总比滥情好
孤独总比滥情好 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: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

提交回复
热议问题