找不到命令时打开的隔离错误
Segfault popen when command not found
编写了一个程序,该程序具有将popen
命令打开到临时文件的方法,读取输出并解析以在程序中的其他地方使用。如果命令成功,程序将按预期工作。但是,如果popen
尝试的命令失败,则文件仍然具有有效的指针,但是当程序尝试读取数据时,程序fgets
seg 错误。
功能主体:
std::map<std::string,size_t> cols;
const char* command = command_string.c_str();
if (FILE *fp = popen(command,"r")) {
char buff[linesize];
std::vector<std::string> list;
std::cout << "here, popen succeededn";
std::cout << fp << 'n';
while (fgets(buff,linesize,fp)) {
std::cout << "here, fgets succeededn";
std::string data(buff);
list.push_back(data);
}
parse_cols(list);
pclose(fp);
}
else {
std::cout << "Failed to open bash shell when trying to run commandn";
std::exit(EXIT_FAILURE);
}
使用输出:
here, popen succeeded
0x1cc2430
sh: my_command: command not found
Segmentation fault (core dumped)
是否可以处理此错误?这是一个有点有用的错误,但我希望能够处理它,而不是仅仅依靠 seg 错误。我尝试查看FILE
结构,但对于不同的 C 库版本似乎有所不同。
Popen是一头野兽。它仅在fork
或pipe
失败时返回nullptr
,但在您的情况下,它们不会。
但是,您的程序不应出现段错误。当 shell 返回失败时,您应该从有效(尽管为空(流中读取。Than fgets()
返回 NULL,因为文件结束发生在未读取任何字符时。
比你调用parse_calls
- 一个我们看不到的函数 - 但我有理由相信它无法处理空列表。在查明实际问题时,崩溃堆栈可能会提供进一步的帮助,这不是popen
或fgets
。
相关文章:
- 从矢量中删除元素后出现隔离错误
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 线程时访问静态映射时出现隔离错误
- 并行快速排序分区中的隔离错误
- C++多线程程序:变量定义为类成员的隔离错误
- TFLite 隔离错误,通过获取C++输入和输出
- 我只是在寻找模板,在我的书中找到了这段代码,这显示了隔离错误?
- pthread_create中错误 4 的隔离错误
- 递归树遍历/分支删除的隔离错误
- 在类模板上使用 arm gcc 编译期间的隔离错误
- 从大量文件读取时出现隔离错误
- 在PHP扩展中使用emalloc从线程时出现隔离错误
- 通过 Boost Python 在C++对象之间传递共享指针的隔离错误
- 在QT中单击菜单时出现隔离错误
- 尝试访问标头声明成员时出现隔离错误
- 搜索链表时出现隔离错误
- 模板化子类析构函数中的隔离错误
- 插件中节点.js/Nan 回调C++不频繁的隔离错误
- 将行添加到 GTKTreeView 时的隔离错误
- 找不到命令时打开的隔离错误