首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从信号处理程序中抛出异常?

从信号处理程序中抛出异常?
EN

Stack Overflow用户
提问于 2018-05-09 08:14:14
回答 2查看 0关注 0票数 0

我们有一个处理错误报告许多方面的库。我一直负责将这个库移植到Linux上。当运行我的小测试套件时,其中一个测试失败。下面显示了一个简化版本的测试。

代码语言:javascript
复制
// Compiler: 4.1.1 20070105 RedHat 4.1.1-52
// Output: Terminate called after throwing an instance of 'int' abort

#include <iostream>
#include <csignal>
using namespace std;

void catch_signal(int signalNumber)
{
    signal(SIGINT, SIG_DFL);
    throw(signalNumber);
}

int test_signal()
{
    signal(SIGINT, catch_signal);

    try
    {
        raise(SIGINT);
    }
    catch (int &z)
    {
        cerr << "Caught exception: " << z << endl;
    }
    return 0;
}

int main()
{
    try
    {
        test_signal();
    }
    catch (int &z)
    {
        cerr << "Caught unexpected exception: " << z << endl;
    }
    return 0;
}

我的期望是被捕获的异常:消息将被显示。实际发生的情况是程序终止,因为抛出的int没有捕获处理程序。

EN

回答 2

Stack Overflow用户

发布于 2018-05-09 17:04:51

信号与C ++的例外完全不同。你不能使用C ++ try / catch块来处理信号。具体来说,信号是POSIX的概念,而不是C ++语言的概念。内核将信号异步传送到应用程序,而C ++异常是由C ++标准定义的同步事件。

你在POSIX信号处理程序中可以轻松执行的操作相当有限。一种常见的策略是sig_atomic_t在信号处理程序中设置一个全局标志类型为1,然后可能longjmp为适当的执行路径。

票数 0
EN

Stack Overflow用户

发布于 2018-05-09 18:08:22

此代码演示了一种将异常抛出信号处理程序的技术移入代码中的技术。

代码语言:javascript
复制
#include <iostream>
#include <csignal>
#include <csetjmp>

using namespace std;

jmp_buf gBuffer;        // A buffer to hold info on where to jump to

void catch_signal(int signalNumber)
{
    //signal(SIGINT, SIG_DFL);          // Switch to default handling
    signal(SIGINT, catch_signal);       // Reactivate this handler.

    longjmp             // Jump back into the normal flow of the program
    (
        gBuffer,        // using this context to say where to jump to
        signalNumber    // and passing back the value of the signal.
    );
}


int test_signal()
{
    signal(SIGINT, catch_signal);

    try
    {
        int sig;
        if ((sig = setjmp(gBuffer)) == 0) 
        {
            cout << "before raise\n";
            raise(SIGINT);
            cout << "after raise\n";

        }
        else
        {
            // This path implies that a signal was thrown, and
            // that the setjmp function returned the signal
            // which puts use at this point.

            // Now that we are out of the signal handler it is
            // normally safe to throw what ever sort of exception we want.
            throw(sig);
        }
    }
    catch (int &z)
    {
        cerr << "Caught exception: " << z << endl;
    }

    return 0;
}

int main()
{
    try
    {
        test_signal();
    }
    catch (int &z)
    {
        cerr << "Caught unexpected exception: " << z << endl;
    }
    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档