send()何时返回小于length参数的值? [英] When will send() return less than the length argument?

查看:79
本文介绍了send()何时返回小于length参数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux上使用阻塞套接字时,是否有任何原因使send()返回的内容少于所请求的内容,其他的内容是否已中断但部分成功的send()系统调用?

When using blocking sockets on Linux, is there any reason for send() to return less than what was requested, other than an interrupted, but partially successful send() syscall?

我知道这可能是非常定义的实现,即使没有安装任何信号处理程序(也就是导致系统调用中断的原因),依靠该行为可能非常危险.我可能会在发送呼叫之前一直循环,直到完成为止.但是,如果对此事有任何官方说法,我将可以避免.

I'm aware that this is possibly very implementation defined, and that it would probably be very dangerous to rely on that behavior even without any installed signal handlers (and thus reasons for interrupted syscalls). I'll probably loop around the send call until completion; however, if there were any official word on the matter, I would be able to avoid that.

为什么是否假设发送返回的数据少于在阻塞套接字上发送的请求数据?在问相同的问题,结果没有定论:提到了中断的系统调用作为返回计数很短的示例,但目前尚不清楚完整的TCP发送缓冲区将导致部分发送,或者send()只会阻塞直到缓冲区中有足够的空间.

Why is it assumed that send may return with less than requested data transmitted on a blocking socket? was asking the same question, with inconclusive results: Interrupted syscalls are mentioned as an example for a short return count, but it's still unclear whether a full TCP send buffer would cause a partial send or the send() would just block until there is enough room in the buffer.

推荐答案

通常,如果传输缓冲区包含一些空间,但不足以容纳整个发送请求,则它将发送尽可能多的空间,然后返回该数量实际上已添加到缓冲区中-简短写入.

In general, if the transmit buffer contains some space, but not enough for the entire send request then it will send as much as it can and then return the amount actually added to the buffer -- a short write.

现在您可能会争辩说,阻塞(在阻塞套接字上)会更有意义,但是它不是历史原因的-TCP基于UNIX管道,这就是UNIX管道的工作方式.主要原因是它使(在内核中)极端情况变得更容易-您不必担心阻塞做某事的系统调用in the middle;它要么做某事然后立即返回,要么什么都不做,直到发生某个事件才阻塞(此时内核从头开始重试).您不必担心如果有人试图在单次写入中写入超出最大缓冲区大小的信息(否则可能会导致死锁).

Now you could argue that it would make more sense to block (on a blocking socket), but the reason it doesn't is historical -- TCP is based on UNIX pipes, and that's the way UNIX pipes worked. The main reason is that it makes corner cases (in the kernel) easier -- you don't have to worry about blocking a system call in the middle of doing something; it either does something and returns immediately or does nothing and blocks until some event (at which point the kernel retries it from scratch). You don't have to worry about what happens if someone tries to write more than the maximum buffer size in a single write (which might otherwise cause a deadlock).

这篇关于send()何时返回小于length参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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