stephenp has asked for the wisdom of the Perl Monks concerning the following question:

When I run this snippet, it runs forever without out ever tripping the sub routine.
$SIG{ALRM} = sub {print "checking;}; alarm 2; while (1) {1};
I would expect this to print out "checking" after about two seconds and then run forever, but it never calls the sub.
I've obviously made a simple, newbie mistake somewhere, but I can't see it.

Replies are listed 'Best First'.
Re: How to use alarm?
by psini (Deacon) on Jul 25, 2008 at 21:10 UTC

    Your program works as you expected (if you close the double quotes) but you can't see the output because STDOUT is buffered. If you change the alarm proc as follows

    $SIG{ALRM} = sub {print "checking;\n"};

    it works.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Re: How to use alarm?
by MidLifeXis (Monsignor) on Jul 25, 2008 at 21:13 UTC

    A couple of items:

    • Please paste actual code. There is an unterminated string after "checking".
    • use strict; use warnings;
    • You are Suffering from Buffering

    That is all before the merits of how alarm is being used (although it looks correct).

    --MidLifeXis

Re: How to use alarm?
by toolic (Bishop) on Jul 25, 2008 at 21:21 UTC
    The documentation for alarm hints at requiring a newline:
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required

    But, it does not offer an explanation :(

      It's because that example is using die (vs. print) and the way die needs \n to avoid printing $! (which will affect the comparison against that die message later in that example).

      The OPs problem is just buffering. Either

      $| = 1; $SIG{ALRM} = sub {print "checking"};
      or
      $SIG{ALRM} = sub {print "checking\n"};
      fixes his problem.

        A last argument to die ending in something other than \n prints the file and line where the die was called, not $!.</pedant>

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.