I am forking a process and need to wait for it to complete, but also need to let the user hit A to abort at any time. My Perl skills are quite limited. Environment: RH 3 (legacy server, with Perl 5.8.0).
I have tried to use an Alarm handler to check for keyboard input every second, so that I can kill the child pid from there if the user presses A, but the problem is that waitpid exits (with -1) the moment the Alarm handler is executed (without any keyboard input, and without executing the kill statement).
Below is a sample to illustrate the issue.
Help would be much appreciated!
#!/usr/bin/perl use strict; use Term::ReadKey; $SIG{ALRM} = "AlarmHandler"; my $childPid = fork(); die unless defined($childPid); if ( ! $childPid ) { # in child sleep 10; exit 0; } # in parent print "\nPlease do xyz (or hit A to abort).\n"; alarm (1); # Check for keystroke every second if (waitpid($childPid, 0) > 0) { my ($rc, $sig, $core) = ($? >> 8, $? & 127, $? & 128); if ($core) { print "PID $childPid dumped core\n"; } elsif ($sig == 9){ print "PID $childPid was killed!\n"; } else { print "PID $childPid returned $rc"; } } else { print "Where did PID $childPid go??"; # When AlarmHandler runs, wa +itpid exits with -1, so gets here. } alarm (0); exit 0; sub AlarmHandler() { open(TTY, "</dev/tty") or die "Failed to open /dev/tty: $!"; my $input = ReadLine -1, *TTY; if ($input ne "") { if ($input =~ /a.*/i) { print "\n\rAborting xyz\n\r"; kill $childPid; } } close(TTY) or die "Failed to close /dev/tty: $!"; alarm (1); # set alarm again }
In reply to Allowing user to abort waitpid by lab007
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |