alf*_*lfC 11 c++ boost process boost-iostreams
在Boost.Process 0.5(http://www.highscore.de/boost/process0.5/index.html)的这个简单示例中,程序(ls)的输出正在输入流.流工作正常但与预期相反,流程在程序完成后不会变为无效(例如,流末尾)(类似于之前版本的Boost.Process,例如http://www.highscore.de/boost /process/index.html)
is在子程序退出后,为了使流(在示例中)自动无效,我缺少什么?
也许我必须在Boost.Streams stream中设置一个选项file_descriptor?
#include <boost/process.hpp> // version 0.5 from http://www.highscore.de/boost/process0.5/process.zip
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <string>
using namespace boost::process;
using namespace boost::process::initializers;
using namespace boost::iostreams;
int main(){
boost::process::pipe p = create_pipe();
file_descriptor_sink sink(p.sink, close_handle);
child c = execute(run_exe("/usr/bin/ls"), bind_stdout(sink));
file_descriptor_source source(p.source, close_handle);
stream<file_descriptor_source> is(source);
std::string s;
while(std::getline(is, s)){
std::cout << "read: " << s << std::endl;
}
std::clog << "end" << std::endl; // never reach
}
Run Code Online (Sandbox Code Playgroud)
2020 年更新: Boost.Process 现在是 Boost https://www.boost.org/doc/libs/1_74_0/doc/html/process.html 的一部分,这个答案可能完全过时了。它仅适用于实验版本“0.5” http://www.highscore.de/boost/process0.5/index.html。
我与图书馆的作者 Boris Schaeling 进行了私下(实际上是通过 Nabble)交流。在排除了几种可能性之后,比如 posix/boost.iostreams 中的错误,他给了我对有效代码的轻微修改。基本上,我可以推断出file_descriptor sink必须超出范围(销毁)才能使流返回 EOF。工作代码只是为sink(在最后列出)添加了一个特定的范围。我认为这可以很容易地将所有内容封装在pistream一种类中。(我列表中的下一步是允许也输出到进程。)
适用于 Boost 1.48 (Fedora 17)。
#include <boost/process.hpp> // version 0.5
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <string>
using namespace boost::process;
using namespace boost::process::initializers;
using namespace boost::iostreams;
int main() {
pipe p = create_pipe();
{
// note the scope for sink
file_descriptor_sink sink(p.sink, close_handle);
/* child c = */ // not necessary to hold a child object, it seems.
execute(run_exe("/usr/bin/ls"), bind_stdout(sink));
} // note the scope for sink
file_descriptor_source source(p.source, close_handle);
stream<file_descriptor_source> is(source);
std::string s;
while(std::getline(is, s)) {
std::cout << "read: " << s << std::endl;
}
std::clog << "end" << std::endl; // never reach
}
Run Code Online (Sandbox Code Playgroud)
编译为 c(lang)++ -lboost_system -lboost_iostreams
编辑:这似乎也有效,它避免了人工范围,但可能会令人困惑,因为接收器必须是临时的:
...
pipe p = create_pipe();
execute(run_exe("/usr/bin/ls"), bind_stdout(
file_descriptor_sink(p.sink, close_handle)
));
file_descriptor_source source(p.source, close_handle);
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |