获取错误消息

时间:2011-03-19 13:00:13

标签: c++ c linux

如何将错误消息的文本从流中获取到变量?

例如

void * thread_func(void ) { 
  char args[]={"firefox","ax",NULL};
  pid_t child_pid = fork();
  if(child_pid!=0) {
    cout<<"error";
  } else {
    execvp("firefox",args); /*something should be done here to get the message*/
  }
  return 0;
}

2 个答案:

答案 0 :(得分:1)

使用strerror()获取errno的字符串。在通话前将errno设置为0,然后进行测试。这样就可以避免令人尴尬的消息,例如臭名昭​​着的'Not a typewriter',这些消息来自printf等良性调用,也可以设置errno。

#include <cerrno>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;

int main()
{
    errno = 0;
    sqrt(-1.0);
    if (errno != 0) {
        string s = strerror(errno);
        cout << s << endl;
    }
}

答案 1 :(得分:0)

您是否在询问类似perror()

的内容