Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I gracefully close my server?

Tags:

c

sockets

I have a server that is listening to stdin (user) and other clients.

Let's say the server is connected to many clients (using select to control all file descriptors), and the user enters EXIT in the terminal. This means the server should close itself.

What is the correct way to close the server gracefully? Should the server go through all file descriptors and close(fd) all of them or just close the listener fd? Alternatively, should I not close anything and just let the server process finish and exit?

I'm using only one thread in my program.

Thank you.

like image 973
Asher Saban Avatar asked Dec 20 '25 22:12

Asher Saban


2 Answers

Closing the listener fd means no more connections will be accepted. The nicest way to handle this would be to:

  • Stop accepting connections
  • Tell everyone to close (through your protocol)
  • Wait for some time and then close the server

Closing a process automatically closes all its open file-descriptors. Telling everyone to close before you exit is just a convenience so as not to abruptly close the connection.

like image 158
cnicutar Avatar answered Dec 22 '25 11:12

cnicutar


For a "graceful disconnect" you should also call shutdown(fd, SHUT_RDWR); ( shutdown() ), so that you can assure that all data is sent and received before you close() the socket.

On a side note, if you're working under linux you might consider using epoll instead of select.

like image 22
lx. Avatar answered Dec 22 '25 12:12

lx.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!