#!/usr/bin/perl -w use strict; # we're abusing signals for this trick $SIG{ALRM} = \&wake_up; start(); sub start { # arbitrary number, could be a variable alarm(5); while (1) { # random time so the handler executes in different spots sleep int rand(3); print "Here's a line after a sleep.\n"; sleep int rand(3); print "Here's a line after another sleep.\n"; # don't interrupt this chunk my $hold = alarm(0); print "Suspending alarm with $hold second(s) left.\n"; sleep int rand(3); print "There should never be an alarm right before this.\n"; # interruptions okay now alarm($hold); sleep int rand(3); print "This is the last line of the loop.\n\n"; } } sub wake_up { # don't interrupt the interrupt (probably unnecessary) $SIG{ALRM} = 'ignore'; print "\t=> in alarm handler <=\n"; # reset alarm alarm(5); # reinstall handler $SIG{ALRM} = \&wake_up; }