perl_lover has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I have one parent process which forks another process through system function. In the parent process I am using /dev/null as STDIN. I want to change the STDIN to tty before forking the child process. How to change the STDIN to tty ?. The forked child process should use the tty as STDIN and the parent should use /dev/null as STDIN

open(STDIN,"/dev/null"); #do some ops #Change STDIN back to tty system("child process"); open(STDIN,"/dev/null");

Replies are listed 'Best First'.
Re: Changing STDIN to tty
by shmem (Chancellor) on Aug 31, 2006 at 09:53 UTC
    Do
    open(STDIN,"</dev/tty")
    before the system call - on *nix, that is...

    But probably you want to use fork:

    open(STDIN,"/dev/null"); #do some ops if((my $pid = fork()) == 0) { # child here open(STDIN,"</dev/tty") or die $!; # do some ops... exit; } else { # parent here - STDIN still is /dev/null # more ops... } # any code hereafter will be executed by parent and, # if the exit in the child block wasn't present, # by the child also

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Changing STDIN to tty
by sgifford (Prior) on Aug 31, 2006 at 15:27 UTC
    Hi perl_lover,

    Now that you have an answer, I'm going to jump into your question and add my own: Does anybody know how to do this portably? In particular, something that will work on both Windows and Unix.

    Thanks!

      Probably reading open is all that is needed :-)

      There's a snippet of code which shows how to dup, redirect and restore STDOUT and STDERR. Should be working for STDIN and with Windows also.

      Could you check? I don't do/have Windows.

      <update> PS: there might be a package on CPAN... :P </update>

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
        Hi shmem,

        Right, I know how to manipulate the filehandles with open, what I don't know is a portable way of saying /dev/tty.

        Thanks!

Re: Changing STDIN to tty
by sgifford (Prior) on Aug 31, 2006 at 15:29 UTC
      I wee bit back, I was offered this snippet of code that might DWYM:
      # untested xp solution to getting interactive input on windows. if($^O eq 'MSWin32') { open(TTY, "CON") or die $!; } else { open(TTY, "</dev/tty") or die $!; }