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

If I trigger an alarm, subsequent reading from a filedescriptor seems broken in an odd way :
$ ./alarmfail.pl 1
TIMEOUT=1
SLEEP=5

(sub1):begin_pos:0
#MAIN, a
#MAIN, b
#MAIN, c
(sub1):sleeping...
(sub1):timed_out!
(sub1):end_pos:52

(sub2):begin_pos:0
(sub2):end_pos:1

(sub2):begin_pos:0
(sub2):end_pos:1
Code works as expected when alarm isn't triggered :
$ ./alarmfail.pl 10
TIMEOUT=10
SLEEP=5

(sub1):begin_pos:0
#MAIN, a
#MAIN, b
#MAIN, c
(sub1):sleeping...
(sub1):end_pos:52

(sub2):begin_pos:0
#MAIN, a
#MAIN, b
#MAIN, c
(sub2):end_pos:52

(sub2):begin_pos:0
#MAIN, a
#MAIN, b
#MAIN, c
(sub2):end_pos:52
Note: The code is an example only, I'm unable to move the inline '#MAIN' tags to a __DATA__ section in my legacy codebase. So perhaps this is a quirk of opening a filehandle to the script itself?
#!/usr/bin/env perl # Example code to show how reading from file descriptors fails after a +n alarm is triggered? use strict; use warnings; my $timeout = defined($ARGV[0]) ? $ARGV[0] : 2; my $sleep = 5; print "TIMEOUT=$timeout\n"; print "SLEEP=$sleep\n\n"; #MAIN, a #MAIN, b #MAIN, c sub sub1 { open(FD1, "$0") or die "ERROR: Could not open $0 : $!\n"; $. = defined($.) ? $. : 0; print "(sub1):begin_pos:$.\n"; while (<FD1>){ next if ! /^#MAIN|^#DATA/; print $_; } eval { local $SIG{ALRM} = sub { die "alarm\n"; }; alarm $timeout; print "(sub1):sleeping...\n"; my $cmd = `sleep $sleep 2>&1;echo slept`; alarm 0; }; if ($@){ print "(sub1):timed_out!\n"; } else { # did not time out } print "(sub1):end_pos:$.\n\n"; close FD1 or die "$!\n"; } sub sub2 { open(FD2, "$0") or die "ERROR: Could not open $0 : $!\n"; print "(sub2):begin_pos:$.\n"; while (<FD2>){ next if ! /^#MAIN|^#DATA/; print $_; } print "(sub2):end_pos:$.\n\n"; close FD2 or die "$!\n"; } &sub1; &sub2; &sub2;

Replies are listed 'Best First'.
Re: alarm and reading from file decriptor
by GotToBTru (Prior) on May 06, 2015 at 14:56 UTC

    I can't duplicate the error; this works as expected in 5.8.8. I do get a subsequent "sh: Broken pipe" error message in the interupted version, probably because the alarm does not close the file handle.

    Dum Spiro Spero
      Seems like it could be a bug with PERL v5.8.4 then, I wonder if there's a workaround...

        Explictly close the file handle in the alarm?

        Dum Spiro Spero
Re: alarm and reading from file decriptor
by Anonymous Monk on May 07, 2015 at 09:05 UTC
      good spot with the '||', but the problem remains... :(
        For the benefit of future students with this problem, I have discovered the answer myself.

        It seems $/ was getting clobbered by the alarm somehow?

        If $/ is saved aside somewhere and restored before each new read, everything is fine again.