in reply to Re^2: Short example using IPC::Open2 or IPC::Open3
in thread Short example using IPC::Open2 or IPC::Open3
It's hard communicating with an interactive application. It might even be impossible without using a pseudo tty if it buffers its output when STDOUT isn't a terminal (like Perl does).
Since sftp can work non-interactively, you'd be better off using calling sftp multiple times, once for each action you wish to perform. open $fr_sftp, '-|', 'sftp', ... would work nicely for that.
But since you're interested in open2 for educational purposes, I'd start with the following.
{ package SFTP; use IO::Handle qw( ); sub new { my $class = shift(@_); my ($to_sftp, $fr_sftp); # open2 dies on error. my $pid = open2($to_sftp, $fr_sftp, 'sftp', @_); $to_sftp->autoflush(1); return bless({ pid => $pid, to_sftp => $to_sftp, fr_sftp => $fr_sftp, }, $class); } sub DESTROY { my ($self) = @_; ...send exit command to child... ...kill child if necessary... waitpid($self->{pid}, 0); } sub do { my ($self) = @_; my $fr_sftp = $self->{fr_sftp}; my $to_sftp = $self->{to_sftp}; print $to_sftp "command"; my $response; for (;;) { my $line = <$fr_sftp>; last if $line =~ $prompt; $response .= $line; } return $response; } } my $sftp = SFTP->new(...sftp args...); my $response = $sftp->do("...\n");
open3 handles STDERR, but that makes the parent code more complicated since it needs to use select to avoid the deadlock that occurs when the child blocks writing to its STDERR and the parent blocks reading from the child's STDOUT and vice-versa.
|
|---|