POSIX:从 UDP 套接字上的 write() 返回值 [英] POSIX: Return value from write() on UDP socket

查看:89
本文介绍了POSIX:从 UDP 套接字上的 write() 返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 POSIX 系统上,如果 sock_fd 是 UDP 套接字,write(sock_fd, data, size) 将始终返回 size 或 -1?即,如果 write() 没有失败,请求的数据块是否总是被完整写入,这意味着,如果返回值不是 -1,那么我可以总是忽略实际的返回值吗?

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.

我想有两个可能的答案.要么在某处声明,但我没有找到它,要么有一些模糊的极端情况,允许返回值小于请求的大小.

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.

推荐答案

与 TCP 和其他传输不同,UDP 仅对整个数据报进行操作.

Unlike with TCP and other transports, UDP operates on whole datagrams only.

write()/send()/sendto()的返回值是内核接受发送的字节数.只是当通过UDP发送数据报时,一次发送整个数据报,或者根本不发送任何内容.因此,成功时返回值将始终为数据报的整个大小,失败时为 -1.没有中间.

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.

与接收相同.read()/recv()/recvfrom() 的返回值是读入用户缓冲区的字节数.只是在通过 UDP 接收数据报时,您要么一次接收整个数据报(如果您的缓冲区太小,数据报将被截断),要么您根本没有收到任何东西.因此,返回值将始终是成功时复制到缓冲区中的数据报的大小,失败时为 -1.没有中间(当然不包括偷看不看的可能性).

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).

这篇关于POSIX:从 UDP 套接字上的 write() 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆