我试图在c中为退出信号创建一个处理程序,我的操作系统是ubuntu.
我正在使用sigaction方法来注册我的自定义处理程序方法.
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
Run Code Online (Sandbox Code Playgroud)
这是我的代码
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我运行程序并按Ctrl + c时,它会显示Inside Inside自定义处理程序.
我已经阅读了sigaction的文档,它说
如果act为非null,则从act安装信号signum的新操作.如果oldact为非null,则先前的操作将保存在oldact中.
当我可以直接赋值时,为什么我需要传递第二个结构
newact = act
Run Code Online (Sandbox Code Playgroud)
谢谢.
oldact
用于重置上一个操作处理程序:
sigaction(SIGINT, ©Interrupted, &previousHandler);
copy(something);
sigaction(SIGINT, &previousHandler, null);
Run Code Online (Sandbox Code Playgroud)
这样,即使您不知道它是什么,也可以重置以前的信号处理程序.
归档时间: |
|
查看次数: |
1670 次 |
最近记录: |