I've recently got bit by doing non-blocking I/O without any sort of buffer checking mechanism. Instead I just keep writing to the filehandle like below:

use IO::Socket::UNIX; $SIG{INT} = sub { unlink "/tmp/sock" }; $srv = IO::Socket::UNIX->new(Local=>"/tmp/sock", Listen=>1); while ($sock = $srv->accept) { $sock->blocking(0); for(1..999){ $sock->syswrite(sprintf "%03d %s\n", $_, "=" x ($_/10)); } $sock->close; }

(Note: the simplified example above doesn't demonstrate why I needed nonblocking).

The full output from the server should be +- 54K. But most of the time the client will only receive +- 12K. With TCP socket instead of Unix, usually only +- 48K.

It is fixed with using select():

use IO::Socket::UNIX; use IO::Select; $SIG{INT} = sub { unlink "/tmp/sock" }; $srv = IO::Socket::UNIX->new(Local=>"/tmp/sock", Listen=>1); while ($sock = $srv->accept) { $sock->blocking(0); $sel = IO::Select->new; $sel->add($sock); for(1..999){ do { @ready = $sel->can_write(1) } until @ready; $ready[0]->print(sprintf "%03d %s\n", $_, "=" x ($_/10)); } $sock->close; }

But I hate having to add those extra lines just to have non-blocking I/O with a single filehandle to work. Is there something simpler like $sock->can_write?


In reply to Non-blocking IO without select()? by dgaramond2

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.