It is difficult to say when alarm will work, when a system call will and will not be interrupted by SIGALRM , how the same code can behave differently in different operating systems, etc.
If your work is over, you want to kill the initial subprocess. This is a good precedent for a poor person's anxiety:
my $pid = open CMD, "$cmd 2>&1 |"; my $time = $MAX_TIMEOUT; my $poor_mans_alarm = "sleep 1,kill(0,$pid)||exit for 1..$time;kill -9,$pid"; if (fork() == 0) { exec($^X, "-e", $poor_mans_alarm); die "Poor man alarm failed to start";
Poor anxiety is triggered in a separate process. Every second, it checks if the process with the id $pid alive. If the process is inactive, the alarm process ends. If the process is still alive after $time seconds, it sends an error signal to the process (I used 9 to make it uncaught and -9 take out the whole subprocess tree, your needs may vary).
( exec may actually not be necessary. I use it because I also use this idiom to monitor processes that can survive the Perl script that launched them. Since this is not the case with this problem, you can skip the exec call and to tell
if (fork() == 0) { for (1..$time) { sleep 1; kill(0,$pid) || exit } kill -9, $pid; exit; }
instead of this.)
source share