# $Id: read_with_timeout.pl,v 1.1 1998/05/01 00:44:57 friedman Exp $

# Usage: read_with_timeout (handle, timeout)
# Returns input if recieved before timeout, undef otherwise.

sub read_with_timeout
{
  local ($handle, $timeout) = @_;
  local ($input);
  local ($old_handler) = $SIG{'ALRM'};

  $SIG{'ALRM'} = 0;  # No need to do anything.
  alarm ($timeout);

  # If the alarm is signalled, this read from the filehandle will be
  # interrupted, and $input will still be undef'ed.
  $input = <$handle>;

  # Cancel current alarm (if any) and restore previous handler (if any).
  alarm (0);
  $SIG{'ALRM'} = $old_handler;

  return $input;
}
