Reputation: 4803
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.
Upvotes: 3
Views: 718
Reputation: 2327
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.
Upvotes: 2
Reputation: 182744
Closing the listener fd
means no more connections will be accepted. The nicest way to handle this would be to:
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.
Upvotes: 4