简体   繁体   English

用C编写的Linux TCP / IP服务器中的Ctrl-C处理

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

I'm currently working on a Linux TCP/IP server. 我目前在Linux TCP / IP服务器上工作。 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. 该服务器程序正在C中运行。我目前正在对其进行测试,但是每次使用Ctrl-c退出该服务器时,它所使用的端口都不会释放,它写入的数据库也不会被解锁。 How does one define a subroutine that will exit when a Ctrl+C signal is received? 如何定义一个子例程,当收到Ctrl + C信号时将退出该子例程?

Two options: 两种选择:

  1. Add a cleanup routine with: int atexit(void (*function)(void)); 添加以下清理例程: int atexit(void(* function)(void));
  2. Hook Ctrl+C with: sighandler_t signal(int signum, sighandler_t handler); sighandler_t signal(int signum,sighandler_t handler)钩住 Ctrl + C ;

As R pointed out, sigaction is more portable than signal , but perhaps less idiomatic for Linux. 正如R所指出的那样, 签名信号更可移植,但对于Linux来说可能更不习惯。

Warning: atexit routines won't run if your program is killed with SIGKILL (Ctrl+/) or any other unhandled signal is received. 警告:如果您的程序被SIGKILL(Ctrl + /)杀死或收到任何其他未处理的信号,则atexit例程将不会运行。

Lookup setsockopt and SO_REUSEADDR . 查找setsockoptSO_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. 必须在旧的原始服务器进程的套接字上设置此选项,否则新的进程将无法绑定端口,直到TIME_WAIT期限到期为止。

@Bortds Generally the port won't be released immediately, you have to wait to for some time. @Bortds通常不会立即释放该端口,您必须等待一段时间。 I found this from a server project I worked. 我从我工作的服务器项目中发现了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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