写入子进程的标准输入

时间:2017-08-31 08:21:22

标签: c++ boost process boost-asio

我正在使用提升过程库。但由于某些原因,我无法向stdin发送内容:

.companymenuul .companymenuli aactive:hover ul{ 
     display:block;
}

我希望这个工作基本上像

#include <iostream>
#include <boost/process.hpp>
using namespace boost::process;

int main(int argc, char** argv) {
    boost::asio::io_service ios;

    std::future<std::string> outdata;
    std::future<std::string> errdata;

    child c("/usr/bin/cat",
            std_out > outdata,
            std_err > errdata,
            std_in < "hi, there!", ios);

    ios.run();
    std::cout << "stdout: " << outdata.get() << std::endl;
    std::cerr << "stderr: " << errdata.get() << std::endl;
}

但是输出是空的。我错过了什么?

1 个答案:

答案 0 :(得分:1)

 std_in < "hi, there!"

打开名为&#34的文件;嗨,那里!&#34;并把它管道给孩子stdin。

比较: Live On Coliru

#include <iostream>
#include <boost/process.hpp>
using namespace boost::process;

int main() {
    boost::asio::io_service ios;

    std::future<std::string> outdata;
    std::future<std::string> errdata;

    child c("/bin/cat",
            std_out > outdata,
            std_err > errdata,
            std_in < "main.cpp", ios);

    ios.run();
    std::cout << "stdout: " << outdata.get() << std::endl;
    std::cerr << "stderr: " << errdata.get() << std::endl;
}

打印自己的源代码。另请参阅boost::process::buffer

的使用

<强> Live On Coliru

  

您显然需要确保stdin在发送缓冲区(?)

后关闭
#include <iostream>
#include <boost/process.hpp>
#include <boost/process/async.hpp>
using namespace boost::process;

int main() {
    boost::asio::io_service ios;

    std::future<std::string> outdata;
    std::future<std::string> errdata;

    async_pipe in(ios);
    child c("/bin/cat",
            std_out > outdata,
            std_err > errdata,
            std_in < in, ios);

    std::string greeting("hi, there!");
    boost::asio::async_write(in, buffer(greeting), [&](boost::system::error_code, size_t) {
                in.close();
            });

    ios.run();
    std::cout << "stdout: '" << outdata.get() << "'\n";
    std::cerr << "stderr: '" << errdata.get() << "'\n";
}

打印

stdout: 'hi, there!'
stderr: ''