[英]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: 两种选择:
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
. 查找
setsockopt
和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. 必须在旧的原始服务器进程的套接字上设置此选项,否则新的进程将无法绑定端口,直到
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.