I would like to achieve the following:
Run a command and capture its output. While waiting for output, run a subroutine every 10 seconds. So, I do not want to escape from the while loop, like in most other examples.
In this example, the timer is set off, but it ends the program. I tried positioning the eval block on various places (e.g. outside the while loop), but to no avail. Perhaps it cannot be done and I need to dive into working with threads.
The sleep 120 in this code is only to simulate no response from command.
#!/usr/bin/perl use strict; use warnings; use Time::Local; use Time::HiRes qw[ time ]; use POSIX ":sys_wait_h"; my $ReturnValue = 0; sub MainSub() { my $Sub = "MainSub"; my $SubReturnValue = 0; my $CommandLine; my $Command = qq(echo 'Hallo, sleeping for 120 seconds ...'; sleep 120 + 2>&1); open (COMMAND, '-|', "$Command"); while (<COMMAND>) { eval { local $SIG{ALRM} = sub { die("TimerTriggerStatus\n"); }; alarm(10); printf "%s : %s\n", scalar localtime(), "$Sub - timer set to 1 +0 seconds"; chomp; $CommandLine = $_; printf "%s : %s\n", scalar localtime(), "$Sub - CommandLine re +ceived:\n$CommandLine"; }; if ( $@ eq "TimerTriggerStatus\n" ) { printf "%s : %s\n", scalar localtime(), "$Sub - timer triggere +d"; &TimerHandler; }; } close (COMMAND); return ($SubReturnValue); } # end of sub MainSub sub TimerHandler() { my $Sub = "TimerHandler"; my $SubReturnValue = 0; printf "%s : %s\n", scalar localtime(), "$Sub - timer expired"; alarm(10); printf "%s : %s\n", scalar localtime(), "$Sub - timer set to 10 second +s"; return ($SubReturnValue); } # end of sub TimerHandler sub TimerSub() { my $Sub = "TimerSub"; my $SubReturnValue = 0; printf "%s : %s\n", scalar localtime(), "$Sub - run after timer interr +upt"; alarm(10); printf "%s : %s\n", scalar localtime(), "$Sub - timer set to 10 second +s"; return ($SubReturnValue); } # end of sub TimerSub #### MAIN #### printf "%s : %s\n", scalar localtime(), "BEGIN - MAIN"; ($ReturnValue) = &MainSub; printf "%s : %s\n", scalar localtime(), "END - MAIN";
Output when run:
# time ./TestSigalrm.pl Wed Jul 24 08:38:20 2019 : BEGIN - MAIN Wed Jul 24 08:38:20 2019 : MainSub - timer set to 10 seconds Wed Jul 24 08:38:20 2019 : MainSub - CommandLine received: Hallo, sleeping for 120 seconds ... Alarm clock real 0m10.018s user 0m0.014s sys 0m0.002s
In reply to Using SIG{ALRM} within while loop. by evroom
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |