2011-03-19 96 views
0

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

例如

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; 
} 
+4

什么错误?什么信息?什么流?什么变量? – ereOn 2011-03-19 13:03:16

+0

请发布代码,你必须显示你想要的是什么。 – Mat 2011-03-19 13:03:33

+0

例如void * thread_func(void) {char _ args [] = {“firefox”,“ax”,NULL}; pid_t child_pid = fork(); (child_pid!= 0) if(child_pid!= 0) cout <<“error”;其他 execvp(“firefox”,args); /*这里应该做些什么来获得消息*/ } return 0; } – Hayk 2011-03-19 13:21:16

回答

0

你是询问像perror()

+0

例如我正在linux中创建一个进程,如果它没有创建,应该在终端中有一条消息,我需要该消息的文本。 – Hayk 2011-03-19 13:18:56

+0

perror将打印出来,但我认为fizzer有正确的想法来存储它。 – jonsca 2011-03-19 13:23:52

1

使用字符串错误()来得到一个错误号的字符串。在打电话之前将errno设置为0,然后再进行测试。这样可以避免像臭名昭着的“不是打字机”这样的令人尴尬的信息,而是来自像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; 
    } 
} 
+2

很难说出你在问什么,尽管 – fizzer 2011-03-19 13:13:17

+0

exec和朋友在失败时设置了errno,所以这对你很有用。 – fizzer 2011-03-19 14:02:31