Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

How to print to STDIN of a cmd and read it's STDOUT

by mhearse (Chaplain)
on May 14, 2013 at 23:28 UTC ( #1033580=perlquestion: print w/replies, xml ) Need Help??
mhearse has asked for the wisdom of the Perl Monks concerning the following question:

I need some help/ideas on scripting an interactive command. Basically my problem is: how do I print to the command and read it's output? The app in question is similar to telnet. And it must remain open as a sub process.
open CMD, "| /usr/bin/whatever |";

Replies are listed 'Best First'.
Re: How to print to STDIN of a cmd and read it's STDOUT
by choroba (Bishop) on May 14, 2013 at 23:32 UTC
    See IPC::Open2.
    #!/usr/bin/perl use strict; use warnings; use IPC::Open2; my $pid = open2(my $OUT, my $IN, "/bin/sed", "s/h/H/"); print $IN "hallo\n"; close $IN; print <$OUT>;


    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks. I also need to block on reading the output after each command is issued. How can I do that? Hmmm... maybe I should just read IPC::Open2 man pages.
Re: How to print to STDIN of a cmd and read it's STDOUT (ouch)
by tye (Sage) on May 15, 2013 at 03:16 UTC

    Good luck with that. :)

    In the general case, you risk deadlock. To avoid deadlock, you run into the areas where Perl 5 tends to disappoint: threads or async I/O.

    Even if you do something either problematically complicated or "less elegant" (writing either the input or the output to a temporary file) in order to avoid deadlock, then you run into the decades-old problem of libc not flushing output the same. (It is a shame that in those decades, libc has still not been taught to flush "like to a TTY" if some environment variable is set.)

    To solve that problem, you either have to have the ability to modify the code being run in the subprocess or you have to deal with pseudo ttys.

    I usually find that the easiest way to deal with pseudo ttys is to ssh to localhost.

    Of course, this is why "expect" was built. But getting a working Perl version of "expect" can be a bit of a challenge (at least the last time I saw somebody try).

    - tye        

Re: How to print to STDIN of a cmd and read it's STDOUT
by Neighbour (Friar) on May 15, 2013 at 09:47 UTC
    You could also try toying with Expect.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1033580]
Approved by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2018-01-21 19:18 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (230 votes). Check out past polls.