问题
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.
回答1:
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).
回答2:
The UDP RFC leaves the implementation details open:
One possible UDP/IP interface would return the whole internet datagram including all of the internet header in response to a receive operation. Such an interface would also allow the UDP to pass a full internet datagram complete with header to the IP to send.
The fact that the POSIX specs don´t go into detail either signifies, to me, that there is no requirement for UDP to use a specific implementation.
Having said that, I´m not aware of any UDP implementation that would handle partial datagrams.
回答3:
There is a return value in bytes. If it was intended to always write the amount you sent it, there wouldn't be a return value in bytes.
So treat it as if it could return anything and you won't have a problem.
Even if you just report an error in a log or abort the program, CHECK THE RETURN.
来源:https://stackoverflow.com/questions/50455967/posix-return-value-from-write-on-udp-socket