Home > Enterprise >  Problem sending text to stdin of running process
Problem sending text to stdin of running process

Time:08-30

I have a c program running with process number PROCNO, and I would like to send text to stdin of this program. However, when I run :

echo test > /proc/PROCNO/fd/0

I see test printed in the console. So, it seems that stdin is being redirected to stdout. How can I prevent this ? The reason is that I would like to read from stdin in my program, but I never get the text.

My stdinlistener is:

void stdin_listener()
{
    std::string line;
    do {
        std::cin >> line;
        std::cout << "received: " << line;
    } while (!line.empty());

}

when I run ls -l on the process no I get

lrwx------. 1 64 Aug 28 17:49 /proc/PROCNO/fd/0 -> /dev/pts/2

CodePudding user response:

How can I prevent this ?

You can't, because this is how terminal devices work on Linux on a fundamental level. When launched from a terminal device, the Linux process's standard input, output, and error, are really the same device:

$ ls -al /proc/$$/fd/[012]
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/0 -> /dev/pts/0
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/1 -> /dev/pts/0
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/2 -> /dev/pts/0

They are three different file descriptors, but all three of them are read/write, and they are all connected to the same underlying device. They can be read/written interchangeably, although traditionally only 0 is read from, and 1 and 2 are written to, but it doesn't matter. But the process can read and write from any of the three file descriptors. Reading from any of these file descriptors reads from the terminal. Writing to them will write to the terminal.

I would like to read from stdin in my program, but I never get the text.

Because reading/writing to the file descriptors reads or writes from the terminal. The End.

If you want to run a process that reads and writes to its standard input and output, and have both the input and the output redirected to your program you will have to create and set up your own terminal device, then launch the program with that terminal device opened as its program standard input and output. See the pty manual page for more information.

  • Related