c - sigaction()中第二个结构(* oldact)的用途是什么

标签 c unix ubuntu

我正在尝试为 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, &copyInterrupted, &previousHandler);
copy(something);
sigaction(SIGINT, &previousHandler, null);

这样,即使您不知道它是什么,您也可以重置之前的信号处理程序。

关于c - sigaction()中第二个结构(* oldact)的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635221/

相关文章:

c - 错误: expected declaration specifiers or ‘...’ before ‘stdin’

c - 打印结构数组

linux - 用于查找文本文件的 Unix 脚本不起作用

c++ - 如何在 C++ 中设置文件权限(跨平台)?

linux - 在一定大小的预文件夹中备份文件

ubuntu - 无法通过我的本地 ubuntu 系统 SCP 到 openshift 帐户

c - 文件系统级别的 SETUID

c - 我应该使堆栈段变大还是堆段变大?

unix - '-a' 在 Unix Shell 脚本中做什么

ubuntu - 在 SSH 中生成文件后无法启动文件