提升进程流为空

Boost process stream is empty

本文关键字:进程      更新时间:2023-10-16

我刚刚安装了 Boost 库,我正在尝试完成基本教程。

我正在尝试打开一个运行g++ --version并将输出通过管道传输到std_ std_out的进程。

代码是从教程中复制的,但进行了以下更改:

  • 添加了cout语句以跟踪进度
  • 添加了对bp::find_executable_in_path()的调用

代码如下:

//
// Boost.Process
// ~~~~~~~~~~~~~
//
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/process.hpp>
#include <string>
#include <vector>
#include <iostream>
namespace bp = ::boost::process;
using namespace std;
bp::child start_child() {
    string exec = bp::find_executable_in_path( "g++" );
    cout << "full path is " << exec << endl;
    cout << "starting child process" << endl;
    vector<std::string> args;
    args.push_back( "--version" );
    bp::context ctx;
    ctx.stdout_behavior = bp::capture_stream();
    ctx.stderr_behavior = bp::capture_stream();
    return bp::launch( exec, args, ctx );
}
int main() {
    bp::child c = start_child();
    bp::pistream &is = c.get_stdout();
    cout << ( is ? "stream is valid" : "stream is NOT valid" ) << endl;
    string line;
    cout << "entering read/write loop" << endl;
    while( getline( is, line ) ) {
        cout << "copying a line" << endl;
        cout << line << endl;
    }
    cout << "exiting read/write loop" << endl;
}

这是我在命令行上运行g++ --version时看到的:

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这是编译程序的输出:

full path is /usr/bin/g++
starting child process
stream is valid
entering read/write loop
exiting read/write loop

它永远不会进入读/写循环。流中的数据发生了什么变化?

您需要输入 gcc 的完整路径,或使用bp::find_executable_in_path("g++")

[编辑]哎呀。在窗户下:

bp::find_executable_in_path("g++.exe")