![]() | |
![]() |
![]() |
![]() | |
![]() | |
Using Expect.pm to Manage an Unreliable Program | |
![]() |
I have a program that I need to run a large number of times. This program has a nasty bug in it. When you feed it bad data, it just sits there forever instead of providing a helpful error message. Bad Program!
I can't change the program, but I need to call this program inside a loop in my code. So I am using the perl Expect module to skip over the problem cases and continue with the rest of the runs of the program.
The Expect.pm module is capable of managing this process, so I wrote a few little test programs to help me understand how to accomplish this task. This document includes the tests along with a few words of explanation. For more documentation about the Expect module, search CPAN.
#!/usr/bin/perl # # Fri Dec 13 23:10:54 PST 2002 # # Copyright Tom Anderson 2002, All rights reserved. # This program may be copied under the same terms as Perl itself. # Please send modifications to t@tomacorp.com # # # unreliable.pl - Simulate a program that sometimes just hangs # my $VERSION=".01"; use strict; use warnings; use diagnostics; if (rand(10) > 8) { sleep 1 while 1 > 0; } else { print "--------------------------------\n", "It worked this time, no problems\n", "--------------------------------\n"; }
#!/usr/bin/perl # # Fri Dec 13 23:10:54 PST 2002 # # Copyright Tom Anderson 2002, All rights reserved. # This program may be copied under the same terms as Perl itself. # Please send modifications to t@tomacorp.com # # timeout.pl - Expect Test Program # use strict; use warnings; use diagnostics; use Expect; my $timeout=5; foreach my $i (1..20) { my $exp = Expect->spawn("/perl//unreliable.html") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout); }
#!/usr/bin/perl # # Fri Dec 13 23:10:54 PST 2002 # # Copyright Tom Anderson 2002, All rights reserved. # This program may be copied under the same terms as Perl itself. # Please send modifications to t@tomacorp.com # # timemsg.pl - Expect Test Program # use strict; use warnings; use diagnostics; use Expect; my $timeout=5; foreach my $i (1..20) { my $exp = Expect->spawn("/perl//unreliable.html") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout, [ timeout => sub { print "Process timed out.\n"; } ] ); }
#!/usr/bin/perl # # Fri Dec 13 23:10:54 PST 2002 # # Copyright Tom Anderson 2002, All rights reserved. # This program may be copied under the same terms as Perl itself. # Please send modifications to t@tomacorp.com # # timecheck.pl - Expect Test Program # my $VERSION=".01"; use strict; use warnings; use diagnostics; use Expect; my $timeout=5; foreach my $i (1..20) { my $spawn_ok="not OK"; my $exp = Expect->spawn("/perl//unreliable.html") or die "Cannot spawn unreliable process $!\n"; $exp->expect($timeout, [ 'It worked', sub { $spawn_ok = "OK"; exp_continue; } ], [ timeout => sub { print "Process timed out.\n"; } ] ); print "Status: $spawn_ok\n"; }