简体   繁体   中英

Writing to File descriptor 0 (STDIN) only affects terminal. Program doesn't read

I'm studying file descriptors and I'm trying to simulate an input for FD 0 (STDIN). I'm testing in a linux environment. My intention is to write, via terminal, simulating an standard input to the code

Here is my python code:

import sys
from os import getpid

print(f'Hello world! Process: { getpid() }')


for line in sys.stdin:
    print(f'Echoing: {line}')

When I try to write into the associated FD 0 in another terminal:

echo "Test" >> /proc/<pid>/fd/0

It only prints in the terminal, the program never reads. I tried to add EOF, break line, heredoc, but I still not find a solution.

Is what I'm trying possible?

Thanks to @Ian Aboot's answers I could find some explanation here:

https://unix.stackexchange.com/questions/385771/writing-to-stdin-of-a-process/385782

According to the answer of the post above:

Accessing /proc/PID/fd/0 doesn't access file descriptor 0 of process PID, it accesses the file which PID has open on file descriptor 0. This is a subtle distinction, but it matters. A file descriptor is a connection that a process has to a file. Writing to a file descriptor writes to the file regardless of how the file has been opened.

and

If /proc/PID/fd/0 is a terminal, then writing to it outputs the data on a terminal. A terminal file is bidirectional: writing to it outputs the data, ie the terminal displays the text; reading from a terminal inputs the data, ie the terminal transmits user input.

Basically I had to control the terminal process to get the input be forwarded into my process. Writing directly to the /dev/pty* didn't work.

Redirecting the input to a fifo, for example, worked as expected. Maybe there is a way to simulate something between the terminal process and the running program itself so I'll keep the research

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM