在Linux下正常关闭服务器套接字 [英] Graceful Shutdown Server Socket in Linux

查看:481
本文介绍了在Linux下正常关闭服务器套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够停止监听在Linux服务器套接字,并确保是从一个客户的角度开放的正确处理,而不是突然关闭所有连接。(如:接收ECONNRESET)

I want to be able to stop listening on a server socket in linux and ensure that all connections that are open from a client's point of view are correctly handled and not abruptly closed (ie: receive ECONNRESET).

例如:

sock = create_socket();
listen(sock, non_zero_backlog);
graceful_close(sock);

如果想调用close(),并处理已经accept'd插座就足够了,但有可能是在内核积压,这将如果你调用close()服务器套接字上突然关闭打开的连接。

if thought calling close() and handling already accept'd sockets would be enough but there can be connections that are open in the kernel backlog which will be abruptly closed if you call close() on the server socket.

推荐答案

的唯一工作方式做到这一点(我发现)是:

The only working way to do that (that I have found) is to:


  1. prevent 接受()增加更多的客户

具有开放式插槽的列表的地方,并要等到他们都正确关闭,这意味着:

have a list of the open sockets somewhere and to wait until they are all properly closed which means:


  • 使用关机()来告诉客户,你将不再是那个插座上工作

  • using shutdown() to tell the client that you will no longer work on that socket

通话阅读()一段时间,以确保所有的客户端已派出
其间一直拉着

call read() for a while to make sure that all the client has sent in the meantime has been pulled

然后用的close()来释放每个客户的插座。

then using close() to free each client socket.

然后,您可以放心地的close()监听套接字。

THEN, you can safely close() the listening socket.

您可以(也应该)使用超时来确保空闲连接不会永远持续下去。

You can (and should) use a timeout to make sure that idle connections will not last forever.

这篇关于在Linux下正常关闭服务器套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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