I just learning how to use SIGALRM, and have run into a little problem that I need your help with. The following code runs as expected on Unix (solaris) and on an MS Win XP desktop, but fails on MS Win Server 2003 R2. I understand that it's a mistake to intermix sleep and alarm, but it's sufficient for this example (the "real" code doesn't "sleep", and has the same problem).
#!/usr/bin/perl -w
use strict;
use warnings;
$| = 1;
$SIG{'ALRM'} = '_ALARM';
$SIG{'QUIT'} = '_QUIT';
my $s_parent = 0;
my $patience_level = 5;
my $doddling_time = 10;
my $child_pid = fork();
if ($child_pid) { # If parent process
$s_parent = 1;
print "Parent: [tapping toe] You have $patience_level seconds to f
+inish your homework ($child_pid)!\n";
alarm $patience_level;
my $job_well_done = wait();
print "Parent: Well, that's over ($job_well_done).\n";
} elsif (defined $child_pid) { # If child process
print "Child.: [doddling...] OK, OK, just $doddling_time more seco
+nds, ...please!?!\n";
sleep $doddling_time;
# The following is unlikely if patience_level < doddling_time
print "Child.: Nana-nana-na-na - all finished ($$).\n";
exit;
} else { # Error on fork
die "!!! Failed to fork !!!..: $!\n";
}
print "The end.\n";
exit;
sub _ALARM {
if ($s_parent) {
print "Parent: Time's up kiddo...\n";
if (kill 0, $child_pid) {
print "Parent: $child_pid is gonna get spanked!\n";
my $spank = kill 'QUIT', $child_pid;
print "Pain level: $spank\n";
} else {
warn "$child_pid has hidden!\n";
}
} else {
print "Child.: Nobody expects the Spanish Inquisition!\n";
}
}
sub _QUIT {
print "Child.: Argh! You didn't have to spank me! ($$)\n";
exit;
}
I expect to see this output:
Parent: [tapping toe] You have 5 seconds to finish your homework (-670
+8)!
Child.: [doddling...] OK, OK, just 10 more seconds, ...please!?!
Parent: Time's up kiddo...
Parent: -6708 is gonna get spanked!
Pain level: 1
Child.: Argh! You didn't have to spank me! (-6708)
Parent: Well, that's over (-6708).
The end.
But on the server in question, I see:
Parent: [tapping toe] You have 5 seconds to finish your homework (-588
+0)!
Child.: [doddling...] OK, OK, just 10 more seconds, ...please!?!
Child.: Nana-nana-na-na - all finished (-5880).
Parent: Well, that's over (-5880).
The end.
My apologies in advance to the non-spankers out there - this was just an effort to make light of a situation that's been frustrating. No children were actually harmed in writing (or executing) this code ;).
Thanks again for your help!