On Jun 14, 3:31 am, gator...@yahoo.de wrote: > Hi, > > On 2011-06-14 09:23, gator...@yahoo.de wrote: > > > > > > > > > > > what I am trying to do is: > > > - run a little program, that just sleeps for a given time > > - when it receives a signal, restarts sleeping again for the > > full time period until it receives another signal or the > > timer elapses. In the latter case it should just exit. > > Something like: > > > sub sleeper { > > warn strftime("%H:%M:%S sleep $sleeptime\n", localtime); > > $SIG{USR1}=\&sleeper; > > sleep $sleeptime; > > }; > > > warn $$; > > sleeper; > > > It sounds very simple, but I can't get it to work as intended. > > ... meanwhile a found a solution; in case somebody with > the same problem stumbles upon this, here's what I came up with: > > my $caught_signal=0; > > sub expired { > warn strftime("%H:%M:%S expired\n", localtime); > exit 0; > > } > > sub sleeper { > warn strftime("%H:%M:%S sleep $sleeptime\n", localtime); > alarm $sleeptime; pause; > > }; > > sub usr1 { alarm 0; $caught_signal=1; } > > $SIG{USR1}=\&usr1; > $SIG{ALRM}=\&expired; > while(1) { > if($caught_signal) { > $caught_signal=0; > } else { > sleeper(); > } > > } > > The problem obviously was, that I called "sleep" from within the > USR1 signal handler and (generally not a bad idea ;) this signal > had been blocked there. > If somebody knows a more elegant solution, let me know ... >
Not sure of your actual program detail but mixing alarm/sleep is a bad idea. See: perldoc -f alarm. Another solution, not necessarily more elegant, but more familiar to most is an eval {} and alarm pair: EVAL: { eval { local $SIG{ ALRM } = sub { die "alarm"; }; local $SIG{ USR1 } = sub { die "usr1" }; alarm $sleeptime; ... some long running operation here .... alarm 0; 1; } or do { alarm 0; if ( $@ =~ /alarm/) { warn "expired..." } } elsif ( $@ =~ /usr1/) { redo EVAL; } } elsif ($@) { die "unexpected error: $@"; } } } -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/