I'm trying to use expect to spawn a program in an automation script in perl.
And I'm trying to decide how to wait on expect for this program to finish, since - I can't rely on any string matching as the program is not consistent with how it exits - I would like to wait on expect until the user prompt is seen and the user gets control.
Is there any means of doing it without performing a regex on the user prompt ? Any flags or exit codes I can rely on which tells the user has control now.
Thanks
It is not stated what else Expect
is used for, or how else the program may indicate its exit.
Assuming that at one point interaction stops and we only wait for the program to exit, you can use expect(undef)
use warnings;
use strict;
use feature 'say';
use Expect;
my $cmd = 'ls -l ./ | head -5; sleep 3';
my $exp = Expect->spawn( $cmd );
say "Started process ", $exp->pid;
$exp->raw_pty(1);
$exp->log_stdout(0);
# ...
$exp->expect(undef);
say "Program exited with status ", $exp->exitstatus;
say $exp->before;
If no output is expected after the program goes incommunicado remove before
.
Another way is to set up a $SIG{CHLD}
signal handler, where you check for the program's PID and set a flag that other code can then check. The PID is in a variable which need be declared before the handler and then set with pid
method after the process is started, so that it is legal (under strict
) to use in the handler and it is set for when the handler runs.
Then exitstatus
isn't useful (-1
) as the process is reaped in the handler.