c++ - 使用 boost 进程获取 shell 命令的标准输出
问题描述
我正在尝试在 C++ 中实现一个运行 shell 命令并返回退出代码的函数,stdout
我stderr.
正在使用Boost process library
std::vector<std::string> read_outline(std::string & file)
{
bp::ipstream is; //reading pipe-stream
bp::child c(bp::search_path("nm"), file, bp::std_out > is);
std::vector<std::string> data;
std::string line;
while (c.running() && std::getline(is, line) && !line.empty())
data.push_back(line);
c.wait();
return data;
}
在 boost 网站的上述示例中,在 while 循环中检查了条件 c.running()。如果进程在到达 while 循环之前完成执行怎么办?在那种情况下,我将无法将子进程的标准输出存储到数据中。Boost 的文档还提到了以下内容
[警告] 警告 如果在 nm 退出后尝试读取,管道将导致死锁
因此,似乎 c.running() 的检查应该在 while 循环中。
如何在程序到达 while 循环之前从完成运行的进程中获取标准输出(和标准错误)?
解决方案
我相信等待电话是为了什么。在此之前,子进程实际上并没有在任何操作系统中消失(它只是在不处于运行状态后改变状态)。
推荐阅读
- c - 是否有一种安全的方法来指定一个对象的值可能因为它从未被使用而未初始化?
- ios - 使用 CallKit 的 TokBox 音频会话问题
- c++ - SDL 和 SDL_image 程序在 Eclipse 中什么都不做
- javascript - 如何使用带有 createTextNode() 的列表的第一个子项
- php - PHP GuzzleHttp 。如何发送 json 帖子?
- android - 解析 UI 层次结构 XML 文件时出错:ubuntu 中的 ui automator 层次结构文件无效
- mysql - GROUP BY Id 和 DATE 时获取 COUNT 的 id
- android - 前台服务在奥利奥 10 分钟后停止提供位置更新
- reporting-services - Reporting Services (SSRS) 删除导出文件的名称
- sql - 在 SQL Server 2008 中使用 case 语句减去 2 行