Reputation: 11762
I have GUI application this application starts server by calling
start_server()
function. Then there is created TCP passive socket receiving incoming connections in the server loop(we have connection sockets here) and handling them on multiple threads simultaneously.
Now I need some end_server() function that force server and all connections to close. What is the best practice to close such servers.
I consider doing this in such way:
start_server()
function some server_info_t
structure. server_info_t
structure there is on_server_start
callback that is called asynchronously after server has been created correctly returning some information about created server like port number on which server is listening (this enable to change GUI controls
like status icon from red to green) server_info_t
info server_loop and there where new connection from client is coming I will take the connection socket and store its descriptor inside server_info_t structure some linked_list_t or hash_map_t of connection sockets. on_client_connected
and pass handling of connection (connection socket) to another function (separate thread from thread pool), and then server loop waits for next connection. I also need to pass server_info_t
structure here to remove connection_socket descriptor from linked_list of conn socket descriptors it connection handling for given client finish. on_client_disconnected
end_server(server_info_t)
(ex. when user clicks STOP in GUI application user interface) and heres the magic happens... server stops. But how? Should I take all connection sockets (while iteration over linked list in server_info_t structure) and close them using (shutdown + close), and then shutdown + close passive socket?
Then I could even call some callback on_server_end
which pointer I found in server_info_t structure.
Should I use some mutex to synchronise access to this server_info_t structure?
Upvotes: 0
Views: 459
Reputation: 3825
Should I use some mutex to synchronise access to this server_info_t structure?
You definitely should synchronize access to the shared data structure.
Should I take all connection sockets (while iteration over linked list in server_info_t structure) and close them using (shutdown + close), and then shutdown + close passive socket?
This is kind of quick and dirty solution. Better design is to inform worker thread the connection should be closed. In this case you can:
Way to solve "inform" task can be different:
select
/poll
/epoll
methods you can use designated socket (for ex. socketpair
) to indicate stoppthread_cancel
mechanisms but they are very system-dependentUpvotes: 1