Often I have a task to read/write data to/from pipes without perl buffered IO (because same pipes used in select()).
AFAIK this should be implemented via sysread/syswrite, and sysread/syswrite are documented to sometimes return less data, than available and sometimes return EINTR (let's talk about blocking pipes for now).
So every time I end up with the following wrappers:
# args: ($file, $buffer, $length)
# returns data in $buffer and number of bytes read, or undef on EOF
sub sysreadfull
{
my ($file, $len) = ($_[0], $_[2]);
my $n = 0;
while ($len - $n) {
my $i = sysread($file, $_[1], $len - $n, $n);
if (defined($i)) {
if ($i == 0) {
return $n;
} else {
$n += $i;
}
} elsif ($!{EINTR}) {
redo;
} else {
return $n ? $n : undef;
}
}
return $n;
}
# args: ($file, $buffer)
# returns number of bytes actually written
sub syswritefull
{
my ($file, $len) = ($_[0], length($_[1]));
my $n = 0;
while ($len - $n) {
my $i = syswrite($file, $_[1], $len - $n, $n);
if (defined($i)) {
$n += $i;
} elsif ($!{EINTR}) {
redo;
} else {
return $n ? $n : undef;
}
}
return $n;
}
Question is: It's should be very common problem for everyone who deals with IPC or network programming, why nobody wrote CPAN module with such wrappers? Maybe because there is easier way ? Maybe ":raw" handles?
I saw similar code only
here (but for non-blocking), but seems it has
bug
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.