[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

Re: [Libvir] take 2 [Re: write(2) may write less than the total requested

Jim Paris <jim jtan com> wrote:
> Jim Meyering wrote:

Hi Jim,

>> -retry:
>> -    ret = write(pollInfos[nr].fd, (char *) req, req->len);
>> +    ret = safewrite(pollInfos[nr].fd, (char *) req, req->len);
>>      if (ret < 0) {
> Should this check (ret == req->len) instead?  safewrite() will return
> an error if write() returns an error, regardless of how many bytes are
> written,

It *could* perform that test, but I think it is slightly more
maintainable (no duplication of that potentially nontrivial expression)
and just as correct to check only "ret < 0".
That's why I made changes like this, too:

-    if (write(fd, TEST_SAVE_MAGIC, sizeof(TEST_SAVE_MAGIC)) != sizeof(TEST_SAVE_MAGIC)) {
+    if (safewrite(fd, TEST_SAVE_MAGIC, sizeof(TEST_SAVE_MAGIC)) < 0) {

Not only that, but the duplication removal makes it more readable because
the reader no longer has to visually ensure that the 3rd arg and the RHS
of the != comparison are the same.  As a bonus, that particular change
brings the line length below the 80-col threshold.

> but it's still possible for it to return less than requested
> if write() returns 0 (eof?).

Really?  How?  EOF is relevant to read, but not to write(2).

As I see it, calling safewrite can have only two outcomes:
  - return -1 to indicate failure
  - return the requested byte count (arg #3, count, which is non-negative)
The only way safewrite can return 0 is if its "count" argument is also 0,
and that's not a failure.  This is because write itself can return 0 only
if its count is also 0.

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]