I'm writing a very simple server that loops forever until Ctrl-C is pressed. I'd like to have the signal handler for ctrl-c close the open sockets and shut down the server, but I don't know what the scope is for a signal handler, and I don't like the idea of declaring the socket(s) I would need to close to be global.
Can someone offer suggestions? Is there some standard way to do this?
Normally, it's advisable not to do anything much in a signal handler; other than set a flag.
Then when control returns to your main loop you can examine this flag, exit the loop, close sockets, run destructors on your objects etc, and exit cleanly.
Signal handlers can get called at almost any time, including in the middle of C or C++ library calls, which could be a problem.
Well, since you have signal handlers, I'm going to assume you're on a Unix variant. If so:
socket(2)
.So, it's perfectly valid in your signal handler. How you make your signal handler aware of which number to use depends on the language you're writing in, which you didn't specify. There are two approaches that will work in pretty much any language
close
and exit, just call exit. Or set the signal action to default, which is exit. The kernel will close the sockets.