user3472537
user3472537

Reputation: 319

How to redirect from terminal stdin to process stdin

My running process handles stdin by using getchar(). It works fine when I run it in foreground. However if I run it in background and do echo "a">> /proc/pid/fd/0 it won't work. On my system, /proc/pid/fd/0 is as same as /proc/pts/0, so how do I send to the process's stdin so that getchar() can see it? I'm working in C++ over ssh.

Upvotes: 5

Views: 901

Answers (1)

myaut
myaut

Reputation: 11514

When you run multiple programs in background, they still have /dev/pts/XX as their control terminal (and stdin), but they are no longer eligible to read from it -- only shell or foreground task can do that. If they do, they'll get SIGTTIN signal that stops background process:

myaut@zenbook:~$ cat &
[1] 15250
myaut@zenbook:~$ 

[1]+  Stopped                 cat

Reasoning for such behavior is simple: multiple programs reading from one source leads to race condition. I.e. when you input to shell who am i, shell will read who, background task #1 will read am and task #2 will read i.

The solution is simple -- do not use pseudo-terminals to transfer data between processes:

  • Use pipes -- unnamed or named (with mkfifo). They are as simple as reading from stdin. Modern shells also provide coprocesses that allow to avoid named pipes.
  • Use UNIX sockets in complex cases
  • If you still need a pseudo-terminal, create a new one for your program with screen or other terminal emulator.

Upvotes: 3

Related Questions