C++ : how to close a tcp socket (server) when receiving SIGKILL

元气小坏坏 提交于 2020-01-05 03:56:05

问题


How can I close a socket just before die? I have a service on linux that create a TCP server. Sometimes I have to restart it and I want that the socket is really closed. At the moment it hangs. I also know that SIGKILL can't be handled. Can anyone point me in the right direction?


回答1:


The socket will be closed - the OS will automatically do this, see: Using SO_REUSEADDR - What happens to previously open socket?

Instead of trying to handle SIGKILL, which won't work, solve the problem at start:

Use the SO_REUSEADDR socket option which allows you to reuse the port immediately.




回答2:


You can't do anything on SIGKILL. You should try to handle SIGTERM and/or SIGINT to terminate your service and close socket.

There is no need to send SIGKILL unless

  1. Application ignores SIGTERM and SIGINT
  2. System really needs to terminate immediately application

When you want to restart your service you should send SIGTERM or SIGINT instead of SIGKILL.



来源:https://stackoverflow.com/questions/21329861/c-how-to-close-a-tcp-socket-server-when-receiving-sigkill

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!