【发布时间】:2010-09-03 11:20:09
【问题描述】:
我正在尝试为 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 的文档,上面写着
如果 act 不为 null,则为 信号signum是从act安装的。 如果 oldact 不为空,则前一个 动作保存在 oldact 中。
当我可以直接分配值时,为什么我需要传递第二个结构
newact = act
谢谢。
【问题讨论】: