Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I do when write(fd, buf, count) returns 0? [duplicate]

Tags:

c

linux

unix

Possible Duplicate:
Is a return value of 0 from write(2) in C an error?

Assuming that count > 0 :

ret = write(fd, buf, count);  
if(ret == 0) {  
    // Should I try to write again
    // or treat this as error?
}

Are there any circumstances in which this condition is possible?

like image 964
Marek Avatar asked Apr 13 '11 22:04

Marek


2 Answers

Unless you explicitly passed a length of zero to write, this will never happen on a correct, POSIX conformant system. If you want to support all kinds of obscure broken legacy proprietary unices, you'll probably have to investigate what happens on each one, and whether the return value of zero is appearing in place of EINTR or in place of EWOULDBLOCK or some other error...

Personally in 2011 I would just assume it doesn't happen. There are a lot of other things which will break much worse trying to support such old broken junk..

Note, per POSIX:

If write() is interrupted by a signal before it writes any data, it shall return -1 with errno set to [EINTR].

http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html

like image 168
R.. GitHub STOP HELPING ICE Avatar answered Nov 10 '22 16:11

R.. GitHub STOP HELPING ICE


The result of the write system call is the total number of bytes written by that system call. In all error cases, it will return -1. Therefore, if the function returns 0 we are in an undefined state (based on the generic docs). I would look for any platform specific reason to be returning 0 and handle it based on the results of that research. If you turn up no platform specific reason, I'd just exit. You're experiencing undefined behavior from a system call, that can't be good.

Man page: http://linux.die.net/man/2/write

like image 28
Thebigcheeze Avatar answered Nov 10 '22 18:11

Thebigcheeze