The way to check if you can write to a socket is, surprisingly, to try and write to it :-)
If the socket has been closed, you will get a -1
return code from write
and you can examine errno
to see what the problem was.
If the socket is still valid but you just can't write any data at the moment, write
will return 0. The read
call also behaves in a similar fashion, returning -1
if there's a problem.
Basically, for write
:
- if you get back a
-1
, there's been a problem and you should check errno
to see if it's recoverable or fatal.
- If you get back a
0
, then you can't write anything at the moment (may be a network backlog or some other problem but definitely not (yet) fatal).
- If you get a value less that what you wanted, then some of the data has been sent. Adjust your pointers so you can try send the rest in the next cycle. Do not assume a positive return value means the entire block has been sent.
- If you get back the same number as the number of bytes you tried to send, the entire buffer has been accepted for delivery.
- If you get back more than what you asked to be sent, send an email off to the kernel developers with some acerbic comment. Linus et al will love that :-)
Update: As caf has pointed out in the comments, I forgot to take into account the signal handling. You have to ignore the broken pipe signal or write
will fail internally by raising that signal.
You can do this by inserting:
struct sigaction new_actn, old_actn;
new_actn.sa_handler = SIG_IGN;
sigemptyset (&new_actn.sa_mask);
new_actn.sa_flags = 0;
sigaction (SIGPIPE, &new_actn, &old_actn);
before starting to use the socket functions. You can then use:
sigaction (SIGPIPE, &old_actn, NULL);
to restore the previous signal handling.