1

Redirect two or more STDOUT to a single STDIN

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

I am assuming if a child process close stdin then parent's stdin gets closed as well and not gettin any user input for code such as :

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

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?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • If you think about it - where would the 'other' STDIN be coming from? How would you differentiate? But you could use a pipe or different filestream. – Sobrique Feb 11 '15 at 19:02

2 Answers2

3

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

No, the child gets a clone of the handle.

$ 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?

Yes. For example, foo <file sets the foo's STDIN rather than having it inherit its parent's.

ikegami
  • 367,544
  • 15
  • 269
  • 518
3

The child process gets duplicates of the parent's standard handles — they are copies, and not the same handle. That means the child can close its STDIN and reopen it as you wish, and you will not affect the parent process at all.

Borodin
  • 126,100
  • 9
  • 70
  • 144