Beefy Boxes and Bandwidth Generously Provided by pair Networks BBQ
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by mhearse (Hermit)
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 |";

Comment on How to print to STDIN of a cmd and read it's STDOUT
Download Code
Re: How to print to STDIN of a cmd and read it's STDOUT
by choroba (Abbot) 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>;

    Output:

    Hallo
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      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 (Cardinal) 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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1033580]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2014-04-18 10:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (465 votes), past polls