You can use alarm
and signal capture the exception that occurs from it. alarm
original intent was socket connections, but it can be used for anything that takes awhile to run:
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
alarm $timeout;
$nread = sysread SOCKET, $buffer, $size;
alarm 0;
};
if ($@) {
print ("Timeout occurred") unless $@ eq "alarm\n"; # propagate unexpected errors
# timed out
}
else {
# didn't
}