each and every socket programming introduction/reference I come across
says that I should loop on write(). Upto now I've been pigheaded about
this, and have refused to believe this to be true for blocking sockets.
Surely, write() will simply block if it can't accept everything
immediately, will it not?
This is (a small part of) the SUSv2 description of write():
ssize_t write(int fildes, const void *buf, size_t nbyte);
[ ... for pipes and FIFOs ... ]
* If the O_NONBLOCK flag is clear, a write request may cause the
thread to block, but on normal completion it will return nbyte.
[ ... ]
When attempting to write to a file descriptor (other than a pipe or
FIFO) that supports non-blocking writes and cannot accept the
* If the O_NONBLOCK flag is clear, write() will block the calling
thread until the data can be accepted.
* If the O_NONBLOCK flag is set, write() will not block the process.
If some data can be written without blocking the process, write()
will write what it can and return the number of bytes written.
Otherwise, it will return -1 and errno will be set to [EAGAIN].
"If the O_NONBLOCK flag is clear, write() will block the calling thread
unti the data can be accepted" is the one I should be relying on, is it
Similarly, from the glibc info manual entry for write():
Normally, `write' blocks until the write operation is
complete. But if the `O_NONBLOCK' flag is set for the file
(note: Control Operations), it returns immediately without
writing any data and reports this error
[ ... but just a bit above that ... ]
The return value is the number of bytes actually written. This
may be SIZE, but can always be smaller. Your program should
always call `write' in a loop, iterating until all the data is written
In addition, my own old winsock code doesn't loop on send(), explicitly
commenting that this isn't necessary since I'm using blocking sockets,
and since I quite clearly remember being very careful about having
verified that to be true back then, I can't believe that UNIX (I'm on
Linux, just in case it makes a difference) would behave differently.
The example code for this group's socket FAQ loops on write(), as does
my "Linux Programming Bible", as does a reference I came across this
afternoon, as does ....
Non of these ever comment on blocking versus non-blocking in this
respect, they just loop. What's the deal with this?