I do not understand why eval() does not trap alarm's die() but I think you have 2 logical errors in your code, in addition to what others spotted:
open (COMMAND, '-|', "$Command"); while (<COMMAND>) { eval { local $SIG{ALRM} = sub { die("TimerTriggerStatus\n"); }; alarm(10); ...
The first is that the while loop may block on the very first time (i.e. before setting the alarm) if your command does not say something at the beginning. In your example it does echo, so this is not happening. The second is inside the loop, when your command has said something, the while condition unblocked and alarm was set. That sets for just once and will expire in 10s but what happens if command blocks again and when the alarm expired it is never re-set?
The code below may have logical errors but it does what I think you want to do and alarm's die() is trapped by eval:
#!/usr/bin/perl use strict; use warnings; use Time::Local; use Time::HiRes qw[ time ]; use POSIX ":sys_wait_h"; my $timeout = 3; my $Command = qq(echo 'Hallo, sleeping for 120 seconds ...'; sleep 120 + 2>&1); my $pid = open (COMMAND, '-|', "$Command"); print "ran command with pid=$pid\n"; my $iters = 0; while (kill 0, $pid) { eval { local $SIG{ALRM} = sub { print "resetting alarm $timeout\n"; a +larm($timeout); die("TimerTriggerStatus\n"); }; if( ! $iters++ ){ print "setting alarm for the first time. +..\n"; alarm($timeout); } print "sleeping for $timeout and then will check command's out +put...\n"; sleep $timeout; print "now I may block for a long time waiting for command's o +utput...\n"; print "command: ".<COMMAND>."\n"; }; print "eval exited with this: ".$@."\n"; }
EDIT: caveat: I am using sleep() but here https://docstore.mik.ua/orelly/weblinux2/modperl/ch06_10.htm states that:
It is usually a mistake to intermix alarm( ) and sleep( ) calls. sleep +( ) may be internally implemented in your system with alarm( ), which + will break your original alarm( )settings, since every new alarm( ) +call cancels the previous one.
bw, bliako
In reply to Re: Using SIG{ALRM} within while loop.
by bliako
in thread Using SIG{ALRM} within while loop.
by evroom
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |