【问题标题】:Forbidden address access in try blocktry 块中的禁止地址访问
【发布时间】:2012-09-12 07:49:27
【问题描述】:

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

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

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

【问题讨论】:

  • C 中没有 try/catch。考虑使用 c++ 标签。
  • 你用什么方法“访问禁止地址”? (你为什么要这样做)?如果你是例如简单地取消引用一个NULL指针,你会在linux下得到一个sigsegv,但不是例外;您可以安装信号处理程序,但这是特定于平台的
  • #nyarlathotep 这不是故意的。我的是一个大型应用程序,其中有很多无效内存访问的机会。就像一个链表的遍历。

标签: c++ linux crash try-catch


【解决方案1】:

尝试访问禁止地址的代码

C++ exceptions 无法捕捉到这一点。只有platform-dependent 解决方案。

【讨论】:

【解决方案2】:

在这种情况下不会产生异常。您需要设置信号处理程序。看看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;
}

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 2015-07-16
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2016-02-17
    • 2017-11-26
    相关资源
    最近更新 更多