找不到命令时打开的隔离错误

Segfault popen when command not found

本文关键字:隔离 错误 命令 找不到      更新时间:2023-10-16

编写了一个程序,该程序具有将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是一头野兽。它仅在forkpipe失败时返回nullptr,但在您的情况下,它们不会。

但是,您的程序不应出现段错误。当 shell 返回失败时,您应该从有效(尽管为空(流中读取。Than fgets() 返回 NULL,因为文件结束发生在未读取任何字符时。

比你调用parse_calls - 一个我们看不到的函数 - 但我有理由相信它无法处理空列表。在查明实际问题时,崩溃堆栈可能会提供进一步的帮助,这不是popenfgets