ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
7.15. Determining the Number of Bytes to ReadProblemYou want to know how many bytes to read from a filehandle with SolutionUse the FIONREAD ioctl call: $size = pack("L", 0); ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size); # $size bytes can be read DiscussionThe Perl Perl's h2ph tool tries to convert C include files to Perl code, which can be require 'sys/ioctl.ph'; $size = pack("L", 0); ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size); If h2ph wasn't installed or doesn't work for you, you can manually grep the include files: % grep FIONREAD /usr/include/*/*
Or write a small C program using the editor of champions: % cat > fionread.c #include <sys/ioctl.h> Then hard-code it, leaving porting as an exercise to your successor. $FIONREAD = 0x4004667f; # XXX: opsys dependent $size = pack("L", 0); ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n"; $size = unpack("L", $size); FIONREAD requires a filehandle connected to a stream, which means sockets, pipes, and tty devices work, but files don't. If this is too much system programming for you, try to think outside the problem. Read from the filehandle in non-blocking mode (see Recipe 7.14). If you manage to read something, then that's how much was waiting to be read. If you couldn't read anything, there was nothing to be read. See AlsoRecipe 7.14; your system's ioctl (2) manpage; the |