在父进程和子进程之间分离 STDIN

Separate STDIN between parent and child process

Redirect two or more STDOUT to a single STDIN

http://en.wikipedia.org/wiki/Standard_streams 说 "More generally, a child process will inherit the standard streams of its parent process."

我假设如果子进程关闭 stdin,那么父进程的 stdin 也会关闭,并且不会获得任何用户输入代码,例如:

if ($select->can_read(1)) {
    my $char = getc();
    if (defined $char) {
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $char\n";
    }
}

父进程是否可以将自己的 STDIN 与子进程的 STDIN 分开,以便子进程可以使用 STDIN 为所欲为,而父进程的 STDIN 不受影响?

I am assuming if a child process close stdin then parent's stdin gets closed as well

不,child 获得句柄的克隆。

$ echo -n 'abcdefghijkl' | perl -e'
   sub r { sysread(STDIN, my $buf, 3); $buf }  # Unbuffered read.
   if (fork()) {
      print "Parent: $_\n" for r();
      sleep(2);
      print "Parent: $_\n" while $_ = r();
   } else {
      sleep(1);
      print "Child: $_\n" for r();
      close(STDIN);
      print "Child: Closed STDIN\n";
   }
'
Parent: abc
Child: def
Child: Closed STDIN
Parent: ghi
Parent: jkl

Can a parent process have its own STDIN separate from child process' STDIN so that a child process can do whatever it wants with STDIN and parent's STDIN does not get affected?

是的。例如,foo <file 设置 foo 的 STDIN 而不是让它继承 parent 的 STDIN。

子进程获得父进程标准句柄的副本 — 它们是副本,而不是同一个句柄。这意味着子进程可以关闭它的 STDIN 并按照你的意愿重新打开它,而你根本不会影响父进程。