As far as I know, the pattern for interrupting something after some time in Perl, is as follows:
#!/usr/bin/perl
local $SIG{ALRM} = sub { die "timed out\n"; };
my $pid;
eval {
alarm 10;
# do stuff
alarm 0;
};
print "done\n";
kill(9, $pid) if $pid;
So one example of a "something" is opening a subprocess for reading which might randomly hang. Simulating it for testing purposes works as expected:
# replace "# do stuff" with:
$pid = open FH, "sleep 120|";
my $line = <FH>;
close FH;
However, these globally-named things can't be passed to other subroutines, so I really want to use the following implementation:
# replace "# do stuff" with:
$pid = open my $fh, "sleep 120|";
my $line = <$fh>;
close $fh;
... but when I run this, the Perl script hangs indefinitely! Why?