问题
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
- Application ignores SIGTERM and SIGINT
- 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