这些天来,我在C中找到了一个提到中止功能的博客。

以下是中止功能的源代码:
http://cristi.indefero.net/p/uClibc-cristi/source/tree/0_9_14/libc/stdlib/abort.c

我发现它使用了hlt指令(我的电脑是x86)。

但似乎hlt必须在环0中运行。
(请参阅Wiki http://en.wikipedia.org/wiki/HLT)

似乎中止正在用户空间中运行。因此,在中止状态中使用hlt指令似乎是非法的。

顺便说一句,我尝试在linux和Windows中运行hlt。但是我遇到一个错误。

在Linux中:

#include <iostream>
using namespace std;

#define HLT_INST asm("hlt")

int main(){
  cout<<"whill run halt"<<endl;

  HLT_INST; //result in SIGSEGV error
  return 0;
}

在Windows中:
cout<<"will run hlg"<<endl;
/*Unhandled exception at 0x0040101d in test_learn.exe: 0xC0000096: Privileged instruction.
*/
__asm{
    hlt;
}

最佳答案

abort函数仅在发送hlt失败后才使用SIGABRT指令。如果您阅读源代码,则该函数首先尝试执行以下操作:

raise(SIGABRT);

然后调用无效指令:
/* Still here?  Try to suicide with an illegal instruction */
if (been_there_done_that == 2) {
    been_there_done_that++;
    ABORT_INSTRUCTION;
}

没错,hlt需要环0特权。这正是使它成为无效指令的原因。执行它会调用一个无效指令处理程序,在您的情况下(我想)是SIGSEGV。

关于c++ - 中止会在环0中运行吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7202732/

10-11 18:33