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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.