On a POSIX system, if sock_fd
is an UDP socket, will write(sock_fd, data, size)
always return size
or -1? I.e., if write()
does not fail, will the requested chunk of data always be written in its entirety, implying that, if the return value is not -1, then I can always ignore the actual return value?
It seems to me that this should be the case, but no man page seems to state it clearly.
EDIT: I suppose there are two possible answers. Either it is stated somewhere, but I haven't found it, or there is some obscure corner case that allows for the return value to be less that the requested size.
Unlike with TCP and other transports, UDP operates on whole datagrams only.
The return value of write()
/send()
/sendto()
is the number of bytes accepted by the kernel for sending. It is just that when sending a datagram over UDP, a whole datagram is sent at one time, or nothing is sent at all. So the return value will always be the whole size of the datagram on success, or -1 on failure. There is no in-between.
Same with receiving. The return value of read()
/recv()
/recvfrom()
is the number of bytes read into the user's buffer. It is just that when receiving a datagram over UDP, you either receive a whole datagram at one time (and if your buffer is too small, the datagram will be truncated), or you don't receive anything at all. So the return value will always be the size of the datagram copied into your buffer on success, or -1 on failure. There is no in-between (not counting the possibility of peeking without reading, of course).