我正在尝试为 c 中的退出信号创建一个处理程序,我的操作系统是 ubuntu。
我正在使用 sigaction 方法来注册我的自定义处理程序方法。
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void CustomHandler(int signo)
{
printf("Inside custom handler");
switch(signo)
{
case SIGFPE:
printf("ERROR: Illegal arithmatic operation.\n");
break;
}
exit(signo);
}
void newCustomHandler(int signo)
{
printf("Inside new custom handler");
switch(signo)
{
case SIGINT:
printf("ERROR: Illegal arithmatic operation.\n");
break;
}
exit(signo);
}
int main(void)
{
long value;
int i;
struct sigaction act = {CustomHandler};
struct sigaction newact = {newCustomHandler};
newact = act;
sigaction(SIGINT, &newact, NULL); //whats the difference between this
/*sigaction(SIGINT, &act, NULL); // and this?
sigaction(SIGINT, NULL, &newact);*/
for(i = 0; i < 5; i++)
{
printf("Value: ");
scanf("%ld", &value);
printf("Result = %ld\n", 2520 / value);
}
}
现在,当我运行程序并按 Ctrl + c 时,它会显示 Inside Inside 自定义处理程序。
我已经阅读了 sigaction 的文档,上面写着
If act is non-null, the new action for signal signum is installed from act. If oldact is non-null, the previous action is saved in oldact.
既然可以直接赋值,为什么还要传第二个结构体
newact = act
谢谢。
最佳答案
oldact
可用于重置之前的操作处理程序:
sigaction(SIGINT, ©Interrupted, &previousHandler);
copy(something);
sigaction(SIGINT, &previousHandler, null);
这样,即使您不知道它是什么,您也可以重置之前的信号处理程序。
关于c - sigaction()中第二个结构(* oldact)的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635221/