7.14. Doing Non-Blocking I/OProblemYou want to read from or write to a filehandle without the system blocking your process until the program, file, socket, or device at the other end is ready. This is desired less often of regular files than of special files. Solution
Open the file with use Fcntl; sysopen(MODEM, "/dev/cua0", O_NONBLOCK|O_RDWR) or die "Can't open modem: $!\n";
If you already have a filehandle, use use Fcntl; $flags = ''; fcntl(HANDLE, F_GETFL, $flags) or die "Couldn't get flags for HANDLE : $!\n"; $flags |= O_NONBLOCK; fcntl(HANDLE, F_SETFL, $flags) or die "Couldn't set flags for HANDLE: $!\n";
Once a filehandle is set for non-blocking I/O, the use POSIX qw(:errno_h); $rv = syswrite(HANDLE, $buffer, length $buffer); if (!defined($rv) && $! == EAGAIN) { # would block } elsif ($rv != length $buffer) { # incomplete write } else { # successfully wrote } $rv = sysread(HANDLE, $buffer, $BUFSIZ); if (!defined($rv) && $! == EAGAIN) { # would block } else { # successfully read $rv bytes from HANDLE } Discussion
The See Also
The |
|