non-blocking input

If you are doing a blocking read() or sysread(), you'll have to arrange for an alarm handler to provide a timeout (see perlfunc/alarm). If you have a non-blocking open, you'll likely have a non-blocking read, which means you may have to use a 4-arg select() to determine whether I/O is ready on that device (see perlfunc/"select".

While trying to read from his caller-id box, the notorious Jamie Zawinski <jwz@netscape.com>, after much gnashing of teeth and fighting with sysread, sysopen, POSIX's tcgetattr business, and various other functions that go bump in the night, finally came up with this:

    sub open_modem {
	use IPC::Open2;
	my $stty = `/bin/stty -g`;
	open2( \*MODEM_IN, \*MODEM_OUT, "cu -l$modem_device -s2400 2>&1");
	# starting cu hoses /dev/tty's stty settings, even when it has
	# been opened on a pipe...
	system("/bin/stty $stty");
	$_ = <MODEM_IN>;
	chomp;
	if ( !m/^Connected/ ) {
	    print STDERR "$0: cu printed `$_' instead of `Connected'\n";
	}
    }

Back to perlfaq8