阻塞的send()是否立即返回? [英] Does a blocking send() returns immediately?

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

问题描述

我认为在阻塞套接字上调用 send()不会返回,直到发送所有数据(直到最后一个数据块被发送到发送缓冲区),但是以下测试显示不同:

  // buffer =AAAAAAAA ... B(10 MB)
char * buffer = new char [10485760];
memset(buffer,0x41,10485760);
buffer [10485758] = 0x42;
buffer [10485759] ='\0';

//发送缓冲区
send(s,buffer,10485760,0);

printf(send()has returned);

所以基本上我连接到Netcat并发送 buffer ,即使 send()已经返回, AAAAAAAAAAAAAA ... 仍然显示在控制台另一端。您可以随时关闭发件人,发送将停止(因此,缓冲区已经到达另一端,但显示它需要很长时间



这只有在发送缓冲区为10+ MB时才有意义。



Edit: send()的返回值为 10485760 (即 c>发送 将数据发送到内核,在那里将其放置在套接字缓冲区中。如果内核用完了套接字缓冲区, send 将会阻塞(或者如果它是非阻塞的,则会失败)。



这与内核向网络发送数据几乎没有关系。



但是,如果你杀死一个程序,它的所有socket都被强行关闭将丢弃任何位于内核缓冲区中的未发送数据。


I thought that calling send() on a blocking socket does not return until all data are sent (until the last chunk of data is sent to the send buffer that is), however the following test showed otherwise:

// buffer = "AAAAAAAA...B" (10 MB)
char *buffer = new char[10485760];
memset(buffer, 0x41, 10485760);
buffer[10485758] = 0x42;
buffer[10485759] = '\0';

// Send buffer
send(s, buffer, 10485760, 0) ;

printf("send() has returned");

So basically I connected to Netcat and sent buffer, and even after send() has returned, AAAAAAAAAAAAAA... was still being displayed to the console on the other end. You can close the sender at any moment and the sending would stop (so it is not that buffer has already arrived to the other end but it takes a long time to display it to the console).

This can only make sense if the send buffer is 10+ MB.

Edit: the return value of send() is 10485760 (i.e. buffer size).

解决方案

send sends the data to the kernel, where it is placed in a socket buffer. If the kernel runs out of socket buffers, the send will block (or fail, if it is non-blocking).

That has very little to do with the kernel sending data to the network.

However, if you kill a program, all of its sockets are forcibly closed, which will discard any unsent data sitting in kernel buffers.

这篇关于阻塞的send()是否立即返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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