try块中的禁止地址访问

时间:2012-09-12 07:49:27

标签: c++ linux crash try-catch

我有一个用户空间代码,如下所示,

try
{
some code
...
code that tries accessing forbidden address
...
some code
}
catch (all exceptions)
{
some logs
}

内核是否会向用户进程发送SIGSEGV信号以进行此无效访问,以及default行为(没有安装任何信号处理程序)。系统会crash吗?

2 个答案:

答案 0 :(得分:1)

  

尝试访问禁止地址的代码

您无法通过C++ exceptions发现此问题。只有platform-dependent解决方案。

答案 1 :(得分:1)

在这种情况下不会生成异常。您需要设置信号处理程序。请查看man signal如何操作。

example

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

static void hdl (int sig, siginfo_t *siginfo, void *context)
{
    printf ("Sending PID: %ld, UID: %ld\n",
            (long)siginfo->si_pid, (long)siginfo->si_uid);
}

int main (int argc, char *argv[])
{
    struct sigaction act;

    memset (&act, '\0', sizeof(act));

    /* Use the sa_sigaction field because the handles has two additional parameters */
    act.sa_sigaction = &hdl;

    /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */
    act.sa_flags = SA_SIGINFO;

    if (sigaction(SIGTERM, &act, NULL) < 0) {
        perror ("sigaction");
        return 1;
    }

    while (1)
        sleep (10);

    return 0;
}