Handling Ctrl-C in a Linux TCP/IP Server written i

2019-07-29 17:05发布

问题:

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:

  1. Add a cleanup routine with: int atexit(void (*function)(void));
  2. 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.



标签: c linux tcp