当使用阻塞套接字时,
send()
函数会一直阻塞,直到最后一个数据传递到本地TCP堆栈的队列中。
因此,
send()
可能在部分数据仍在本地TCP堆栈中排队时返回。由于您的进程在
send()
调用之后退出,在退出期间本地TCP堆栈中可能存在未传递的数据。
如果启用了延迟关闭功能,则TCP堆栈可能会在退出后继续数据传输。如果禁用了延迟关闭功能,则TCP堆栈可能会重置连接而不尝试将未传递的数据传输到对等方。
如果启用了延迟关闭功能并优雅地关闭TCP连接,则TCP堆栈应该(尝试)将排队的数据传递给对等方。
通过添加
close()
调用来优雅地关闭连接。并确保启用了合理的超时时间的SO_LINGER:
send(socket,buffer, 1024*1024*1024,0);
const struct linger linger_val = { 1, 600 };
setsockopt(socket, SOL_SOCKET, SO_LINGER, &linger_val, sizeof(linger_val));
close(socket);
return 1;
通常情况下,不需要更改SO_LINGER。有关SO_LINGER的更多信息,请参阅socket(7)手册页:
SO_LINGER
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
socket
函数。如果您使用POSIX套接字,请添加适当的标签[tag:posix]。 - phuclv