c - 信号处理程序在执行后结束进程
问题描述
我正在编写一个程序,并为以下内容设置了一个信号处理程序SIGINT
:
volatile int exit_program = 0; //Global variable
void exit_client() {
write(1, "Disconnecting...\n", strlen("Disconnecting...\n"));
exit_program = 1;
}
然后我主要告诉进程在收到exit_client()
a 时做出反应。SIGINT
int main() {
signal(SIGINT, exit_client);
//...
}
稍后在主要过程中,我有以下代码:
while (!exit_program) {
//...
socket_rcv(server_socket);
}
close(server_socket);
write(1, "Disconnected\n", strlen("Disconnected\n"));
我用来socket_rcv()
从服务器套接字接收数据,如果返回值为 0(当服务器断开连接时) ,我也会向SIGINT
进程发送一个。read()
我这样做执行: raise(SIGINT)
:
socket_data socket_rcv(int socket) {
//...
do {
bytes_read = read(socket, sequence + (115 - total_bytes), total_bytes+10);
if (bytes_read == -1) write(1, "Read error\n", strlen("Read error\n"));
if (bytes_read == 0) raise(SIGINT);
total_bytes -= bytes_read;
} while (total_bytes > 0);
//...
}
但是,当同时执行服务器和客户端并首先断开服务器连接时,为了查看客户端的反应(应该打印Disconnecting...
然后Disconnected
服务器套接字关闭),我只在信号处理程序中打印以确认信号处理程序执行但是随后程序终止并且它不会继续执行以关闭套接字并执行最后一个write(1, "Disconnected\n", strlen("Disconnected\n"));
。
为什么它会终止,我该如何解决?
此外,可能无关紧要,但socket_rcv()
函数是在另一个.c
文件中声明的,包括.h
主进程所在的模块。
解决方案
我同意评论者的观点,为什么可以exit_program
直接设置信号处理程序?
无论如何,你的问题似乎在其他地方(也许read
?)或者你没有给我们完整的图片,因为这段代码有效:
#include <signal.h>
#include <string.h>
#include <unistd.h>
volatile int exit_program = 0;
void exit_handler(int sig) {
write(1, "exit_handler\n", strlen("exit_handler\n"));
exit_program = 1;
}
int main() {
int i = 0;
signal(SIGINT, exit_handler);
while (!exit_program) {
write(1, "loop\n", strlen("loop\n"));
if (i == 1) {
raise(SIGINT);
}
++i;
}
write(1, "done\n", strlen("done\n"));
return 0;
}
印刷
loop
loop
exit_handler
done
推荐阅读
- openedge - 是否可以使用 .PF 文件以编程方式连接到数据库
- java - Javapackager - 包含 Java 可执行文件
- oracle - 动态 sql、绑定变量和动态 USING
- javascript - 等待后导出 ES6 模块
- json - 动态更新 JSON 对象值并将它们存储在 BASH 中的新文件中
- javafx - JavaFX FXML setUserData DAO
- laravel - 我的查询不起作用
- android - 存根索引指向没有 PSI 的文件:com.intellij.openapi.fileTypes.UnknownFileType@23713b43
- javascript - 使用 jquery 从 html 克隆中删除元素标记时出现错误
- sql-server - 使用 REPLACE 函数创建 SQL Server 函数