我已经构建了一个函数(基于一个例子),它允许我忽略信号SIGINT
。该功能计算用户按CONTROL + C
(中断SIGINT
)的时间。该功能如下
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
sig_atomic_t sigint_count = 0;
void handler (int signal_number)
{
++sigint_count;
printf ("SIGINT was raised %d times\n", sigint_count);
}
int main ()
{
struct sigaction sa; //Declaração da estrutura sigaction
memset (&sa, 0, sizeof (sa));//Libertação da memória usada
sa.sa_handler = &handler;
sigaction (SIGINT, &sa, NULL);
while(1);
return 0;
}
我怀疑这行代码
sigaction (SIGINT, &sa, NULL);
我试着写另一个与NULL
不同的东西,但它不起作用。为什么NULL
? NULL
中sigaction
的含义是什么?
PS:它可以正常运作
答案 0 :(得分:0)
声明的声明是:
int sigaction(int signum, const struct sigaction *act,
struct sigaction *oldact);
旧的操作,即您要替换的操作,将写入第三个参数中的指针。如果您不需要此结果,则可以提供NULL以忽略它。
如果oldact为非NULL,则先前的操作将保存在oldact中。
获取旧操作对于暂时替换它很有用。
例如,修改代码如下:
volatile sig_atomic_t sigint_count = 0;
...
struct sigaction backup;
sigaction (SIGINT, &sa, &backup);
while(sigint_count < 10) {}
sigaction (SIGINT, &backup, NULL);
printf("^C again will terminate me.\n");
while(1){}
如果sig_atomic_t
变量是从并发上下文访问的,则将其声明为volatile
。如果你不这样做,编译器可能会&#34;缓存&#34;寄存器中的值和while(<)
是无穷无尽的