如何防止(不响应)分段错误? [英] How can I prevent (not react to) a segmentation fault?

查看:84
本文介绍了如何防止(不响应)分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不尝试处理细分错误.我了解异常处理的工作原理,或多或少.首先,我宁可没有错.我想做的是调用一个函数或执行一个操作,该操作返回一个值,该值告诉我是否可以访问该特定的内存位置/块,而无需实际访问它并获取错误.

I am not trying to handle a segmentation fault. I understand how exception handling works, more or less. I would rather not have the fault in the first place. What I want to do is call a function or perform an operation that returns a value telling me whether or not that particular memory location/block is accessible, without actually accessing it and getting the fault.

也就是说,我希望C函数在实际访问地址之前先探测Linux和/或Mac OS X中的地址.像这样:

That is, I would like a C function to probe an address in Linux and/or Mac OS X before actually accessing it. Something like:

result = probe_memory(address,length)

结果在哪里

 0 = writable
 1 = read-only
-1 = nonexistent

或类似的内容.

Linux和/或Mac OS X中有类似的东西吗?

Is there anything like that in Linux and/or Mac OS X?

推荐答案

我相信类似以下内容的东西应该可以工作:

I believe something more or less like the following should work:

int probe_memory(void *address, size_t length) {
    int result, fd[2];

    pipe(fd);  /* Remember to check for errors! */

    errno = 0;
    result = write(fd[1], address, length);

    if (result < 0 || (size_t)result != length || errno == EFAULT) {
        result = 0;
    } else {
        result = 1;
    }

    close(fd[0]);
    close(fd[1]);

    return result;
}

这是对您的问题的部分解决方案,因为此代码不会检查页面保护.

基本思想是让操作系统通过对write的调用从address中读取length个字节.如果无法访问内存,它将返回EFAULT而不触发段错误.

The basic idea is to let the OS read length bytes from address through the call to write. If the memory is not accessible, it will return EFAULT without triggering a segfault.

Jonathan Leffler 在他的 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆