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:
If you need help understanding this code or have further problems, feel free to ask.#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);
In reply to Re: Usage of IPC::Open2 ...
by repson
in thread Usage of IPC::Open2 ...
by galande
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |