my $buffer;
while (1) {
read( PORT, $byte, 1 );
$buffer .= $byte;
if ( length( $buffer )) {
printf( "Buffer now has %d bytes; last byte read was 0x%02x\n"
+,
length( $buffer ), $byte );
}
}
You can kill that process (i.e. ^C or some other method) when you feel that it has run long enough so you know what's going on. Then you can add logic inside the while loop so that when the input buffer attains some particular state (or the last byte was some particular value), you break out of the loop and do something else.
The term "discipline" applied to reading from a file handle covers things like: (a) how to delimit input records (i.e. either by number of bytes, or by watching for a particular byte value or byte sequence; and (b) whether or not your process should wait for data when it tries to read (i.e. using a "blocking" vs. "non-blocking" read - "blocking" is the default).
It's been a while since I've tried to play with non-blocking reads, but you should be able to look that up. The basic idea is that when "read" is called, it always returns pretty much right away; if the device has data to be read, your input buffer gets the data, otherwise your input buffer remains empty and your process continues to execute. This is how people handle devices where input data arrives at unpredictable intervals, but other things have to be done while waiting for input.
The example above assumes blocking input (read doesn't return until the device has delivered a byte to be read). If you were to convert it to use a non-blocking input, you'd want to set $byte to empty string or undef before the read call, then check if it contains a value after the read; if it does, then append to the buffer and print the report. (When using non-blocking input, it can also a good idea in many cases to include a "sleep()" call, to keep the loop from consuming too many cpu cycles.) |