I'm currently working on a Linux TCP/IP server. The server program is running in C. I'm currently testing it, but each time I exit it with Ctrl-c, the port it's using is not released, neither is the database it's been writing to unlocked. How does one define a subroutine that will exit when a Ctrl+C signal is received?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Lookup setsockopt
and SO_REUSEADDR
. This option must have been set on the old original server process's socket or the new one will not be able to bind the port until the TIME_WAIT
period expires.
回答2:
@Bortds Generally the port won't be released immediately, you have to wait to for some time. I found this from a server project I worked.
回答3:
Two options:
- Add a cleanup routine with: int atexit(void (*function)(void));
- Hook Ctrl+C with: sighandler_t signal(int signum, sighandler_t handler);
As R pointed out, sigaction is more portable than signal, but perhaps less idiomatic for Linux.
Warning: atexit routines won't run if your program is killed with SIGKILL (Ctrl+/) or any other unhandled signal is received.