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

2

2

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?

Dicentra answered 24/1, 2014 at 10:10 Comment(0)
A
5

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.

Androgen answered 24/1, 2014 at 10:42 Comment(1)
Thanks a lot. I added: int optval=1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);Dicentra
K
0

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.

Kaduna answered 24/1, 2014 at 10:15 Comment(1)
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.