问题
I've been trying to send data to stdin of a running process. Here is what I do:
In a terminal I've started a c++ program that simply reads a string and prints it. Code excerpt:
while (true) { cin >> s; cout << "I've just read " << s << endl; }
I get the PID of the running program
- I go to
/proc/PID/fd/
- I execute
echo text > 0
Result: text
appears in the terminal where the program is run. Note, not I've just read text
, but simply text
.
What am I doing wrong and what should I do to get this thing to print 'I've just read text'
?
回答1:
When you're starting your C++ program you need to make sure its input comes from a pipe but not from a terminal. You may use cat | myapp
to do that. Once it's running you may use PID of your application for echo text > /proc/PID/fd/0
回答2:
It could be a matter of stdout
not being properly flushed -- see "Unix Buffering". Or you could be in a different shell as some commentators have suggested.
Generally, it's more reliable to handle basic interprocess communication via FIFOs or NODs -- named pipes. (Or alternatively redirect stdout
and/or stderr
to a file and read from that with your c++
program.)
Here's some good resources on how to use those in both the terminal and c++
.
"FIFO – Named pipes: mkfifo, mknod"
"Using Pipes in Linux Processes"
"Programming with FIFO: mkfifo(), mknod()"
回答3:
FD 0 is the terminal the program is running from. When you write to FD 0, you are writing to the terminal the program is running from. FD 0 is not required to be opened in read-only mode; in practice it seems to be read/write mode, so you can write to it. (I suspect this is because FDs 0, 1 and 2 all refer to the same file description)
So echo text > /proc/PID/fd/0
just echoes text
to the terminal.
To pipe input to the program, you would need to write to the other end of the pipe (actually a PTY, which mostly behaves like a pair of pipes). Most likely, whatever terminal emulator you're using (xterm, konsole, gnome-terminal) will have the other end open, so you could try writing to that.
来源:https://stackoverflow.com/questions/37424497/sending-data-to-stdin-of-another-process-through-linux-terminal