doing away with the server loop

for writing server programs, there usually is an infinite loop meant to accept connections and process them and when I want to end the server I would normally have to ctrl-c, I find this very inelegant, is there a better way to exit gracefully?
Yes. Your program should look to see if another copy of itself is already running when it starts.
If so, and if your program is activated to terminate, then it sends the other copy a message which means "terminate".

So, for example, using the server might work something like:

$ myserver&
$ myclient
(ping successful)
$ myserver -quit
$

The first copy of the server runs in the background...
The client simply pings the server and prints whether or not it worked
The second copy of the server tells the first copy to quit (which it does).

Hope this helps.
Under Unix, a implementing a signal handler in the server is the simplest way to do this.

From the command line you can say, kill -2 process_id to have the program exit cleanly.
Last edited on
For things like RPC server, it's also common, that you provide a remote procedure "shutdown" and you contact your server over its own serving interface.

Ciao, Imi.
Just because you kill with ^C, it doesn't have to be ugly. You could override the default SIGINT handler and have it set a volatile variable that's periodically checked by a loop. It's not a whole lot nicer, but it at least gives the server a chance to save state if it has to.
Topic archived. No new replies allowed.