【问题标题】:What is the use of second structure(*oldact) in sigaction()sigaction() 中的第二个结构(*oldact) 有什么用
【发布时间】: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

谢谢。

【问题讨论】:

    标签: c unix ubuntu


    【解决方案1】:

    oldact 有助于重置之前的操作处理程序:

    sigaction(SIGINT, &copyInterrupted, &previousHandler);
    copy(something);
    sigaction(SIGINT, &previousHandler, null);
    

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

    【讨论】:

    • 对不起,我是一名学习者。为什么我们需要重置以前的信号处理程序?不能手动重置吗?或者它是一个额外的功能?
    • @Searock 第三行代码正在重置之前的处理程序。
    • @manneorama 感谢您的回复,但我的主要问题是为什么我必须使用 sigaction 方法重置以前的处理程序?我不能像普通结构一样重置它吗?
    【解决方案2】:

    当您调用sigaction 时,您用新的处理程序替换旧处理程序; oldact 指针设置为指向在此替换之前有效的处理程序信息。

    也许,通常情况下,您希望新的处理程序仅对代码的有限区域有效:既然您知道更改之前的配置是什么,您可以通过另一个调用来恢复它sigaction,在这个区域的末尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2021-07-22
      • 2013-09-29
      • 1970-01-01
      • 2020-07-31
      相关资源
      最近更新 更多