简体   繁体   中英

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

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?

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.

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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM