Okay I can see several issues with your code.

First off what you are actually doing here can be done with a simple qx// or backticks. print qw/$cmd/ could replace your loop. This code would be much more sensible than what you are doing if what you intend is simply to get the output of running $cmd.

Note: You should be running with taint checks on when running user input in the shell if there is more to this program then simply providing a direct wrapper around bash from the shell.

However if you require a persistent shell (though I don't see why you would in normal situations) then you are on the right track. The first problem is that for a persistent shell you would want to move open2 and the autoflush statements outside the loop. You should also print more than one line of output from the shell in the loop.
Here is my code to accomplish this task:

#same initialization my $pid = open2( \*Reader, \*Writer, "/bin/bash" ) or warn $!; Writer->autoflush(); Reader->autoflush(); STDIN->autoflush(); $SIG{ALRM} = sub {die}; # required for alarm call below do { print ": "; # simple prompt my $cmd = <STDIN>; print Writer $cmd; my $got; while (1) { eval { alarm 3; $_=<Reader> }; # get line in 3 seconds or stop + reading alarm 0; last if ($@ or !(defined($_))); # exit loop if there was a tim +eout or no data $got .= $_; } print $got; } while(1);
If you need help understanding this code or have further problems, feel free to ask.

In reply to Re: Usage of IPC::Open2 ... by repson
in thread Usage of IPC::Open2 ... by galande

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.