I have a classic TCP server that accepts connections with system call accept()
.
In a specific situation I have n connections accepted and so n childs created.
I need to stop connection when generic event A occurs on the server. What is the best way to close socket in server and in client?
Now I do it such way: when event A occurs, server sends a specific message to client and then it executes close()
. Client reads socket and if the message is the special message it closes.
But if I need to do something else in the client this way is very bad. What can I do?

- 71
- 9
-
You can switch from a process-per-client model to a single process that manages the connections using `epoll` / `kqueue` / `poll` / `select` (IO event monitoring functions). You will save resources and will make it easier to gracefully manage server-wide events (such as a shutdown). – Myst Jul 22 '19 at 23:06
1 Answers
By 'n childs created' I assume you mean n child processes, with each child process handling the TCP connection to one client program?
If so, one way to handle it would be to have your server's parent-process keep track of the process IDs (as returned by fork()
) of the child processes it has spawned (via a list or lookup-table or similar). Then when you need a particular connection to go away, your server's parent-process can call kill(the_child_process_id, SIGTERM)
or similar to get the child-process to go away ASAP. (SIGTERM asks nicely; if you want to go full-nuclear you could specify SIGKILL instead).
In any case, once the child-process on the server has received the signal and exited, the OS will make sure that the server's side of the TCP connection is closed, and the client's OS will then be notified that the TCP connection is closed, and based on that, the client (if it is coded correctly to handle remote-closed connections, i.e. to react to recv()
returning 0 by closing its own TCP socket) will then do the right thing as well.

- 70,199
- 15
- 131
- 234
-
So I need to execute recv() on the client and check if recv() returns 0. Can Client know that TCP server child is ended without executes recv()? For example receive a particular signal? Thanks!! – ABC Jul 23 '19 at 10:44
-
See: https://stackoverflow.com/questions/17705239/is-there-a-way-to-detect-that-tcp-socket-has-been-closed-by-the-remote-peer-wit – Jeremy Friesner Jul 23 '19 at 13:33