【Linux】信号3——信号的捕捉
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在Linux系统中,可以使用sigaction
函数来设置信号的处理方式,包括捕捉(capture)信号。以下是一个简单的示例,展示了如何捕捉SIGINT信号(当用户按下Ctrl+C
时发出)并打印一条消息。
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void handle_sigint(int sig) {
write(1, "Captured SIGINT\n", 16);
}
int main() {
struct sigaction sa;
sa.sa_handler = &handle_sigint;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
while(1) {
pause(); // 暂停进程直到信号到来
}
return 0;
}
在这个例子中,我们定义了一个信号处理函数handle_sigint
,当捕捉到SIGINT信号时,它会打印一条消息。然后我们使用sigaction
函数来设置信号处理动作,捕捉SIGINT信号。程序会一直循环等待,直到有信号发生。当用户发送SIGINT信号(比如按下Ctrl+C
),程序会调用handle_sigint
函数来处理该信号。
评论已关闭