I have a server that is listening to stdin (user开发者_Python百科) 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.
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.
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.
精彩评论