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?
C++ : how to close a tcp socket (server) when receiving SIGKILL
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.
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.
Ok, I add an handler to SIGINT (SIGTERM was handled yet). I use restart from upstart to deactivate and re activate the server. –
Dicentra
© 2022 - 2024 — McMap. All rights reserved.
int optval=1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
– Dicentra