I'm working on a little server that tails a file and listens to socket connections to which it relays info about that file. I've been playing around with doing non-blocking reads from both the filehandle and the socket, using IO::Select. Or rather, "semi-blocking" in that I want don't want to block on any particular handle, but I do want to block when there's nothing on any handle to keep CPU usage down.

So, I push my handles into the IO::Select object and supposedly both IO::Select->can_read() and IO::Select->select($handles, undef, undef, 0) are supposed to block until any one of the handles has some data, e.g.:

can_read ( [ TIMEOUT ] ) Return an array of handles that are ready for reading. "TIMEOU +T" is the maximum amount of time to wait before returning an empty l +ist, in seconds, possibly fractional. If "TIMEOUT" is not given and + any handles are registered then the call will block.

But when I try this, it doesn't block on the filehandle, and keeps looping with no new data in the file. Here is my sample minimal code where I am only working with the file handle and no TCP sockets:

#!/usr/bin/perl use IO::Select; open $fh, '/tmp/test_file'; $sel = new IO::Select( $fh ); while(@ready = $sel->can_read) { print "looping\n"; foreach $h (@ready) { if ($h == $fh) { print "reading from fh\n"; while ($buf = <$h>) { print $loop++," $buf"; } } else { print "handle is unknown\n"; } } }

This tails my file just fine, but it doesn't block when the file is not changing. Any suggestions?

(I do know about File::Tail, in case anyone was going to suggest that, but I couldn't see how to implement it non-blocking and integrate that with the socket listener.)

Thanks.


In reply to blocking, non-blocking, and semi-blocking by genecutl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.