C++ 无法使用Boost.process捕获进程的标准输出
目前我正在使用Boost沙箱中的Boost.Process,在获取它以正确捕获我的标准输出时遇到问题;想知道是否有人能给我第二双眼睛看看我可能做错了什么 我正在尝试使用DCRAW(最新版本)从原始相机图像中提取缩略图,并捕获它们以转换为QT-QImage 流程启动功能:C++ 无法使用Boost.process捕获进程的标准输出,c++,windows,boost,io-redirection,C++,Windows,Boost,Io Redirection,目前我正在使用Boost沙箱中的Boost.Process,在获取它以正确捕获我的标准输出时遇到问题;想知道是否有人能给我第二双眼睛看看我可能做错了什么 我正在尝试使用DCRAW(最新版本)从原始相机图像中提取缩略图,并捕获它们以转换为QT-QImage 流程启动功能: namespace bf = ::boost::filesystem; namespace bp = ::boost::process; QImage DCRawInterface::convertRawImage(stri
namespace bf = ::boost::filesystem;
namespace bp = ::boost::process;
QImage DCRawInterface::convertRawImage(string path) {
// commandline: dcraw -e -c <srcfile> -> piped to stdout.
if ( bf::exists( path ) ) {
std::string exec = "bin\\dcraw.exe";
std::vector<std::string> args;
args.push_back("-v");
args.push_back("-c");
args.push_back("-e");
args.push_back(path);
bp::context ctx;
ctx.stdout_behavior = bp::capture_stream();
bp::child c = bp::launch(exec, args, ctx);
bp::pistream &is = c.get_stdout();
ofstream output("C:\\temp\\testcfk.jpg");
streamcopy(is, output);
}
return (NULL);
}
inline void streamcopy(std::istream& input, std::ostream& out) {
char buffer[4096];
int i = 0;
while (!input.eof() ) {
memset(buffer, 0, sizeof(buffer));
int bytes = input.readsome(buffer, sizeof buffer);
out.write(buffer, bytes);
i++;
}
}
目标是简单地验证我是否可以将输入流复制到输出文件
当前,如果我注释掉以下行:
args.push_back("-c");
然后DCRAW将缩略图写入名为CFK_2439.thumb.jpg的源目录,这向我证明了该进程是使用正确的参数调用的。没有发生的是正确连接到输出管道
FWIW:我正在Eclipse3.5/LatestMingW(GCC4.4)下的WindowsXP上执行这个测试
[更新]
通过调试,当代码到达streamcopy时,文件/管道似乎已经关闭-bytes=input。readsome(…)永远不是0以外的任何值。我认为您需要正确重定向输出流。在我的应用程序中,类似于这样的工作方式:
[...]
bp::command_line cl(_commandLine);
bp::launcher l;
l.set_stdout_behavior(bp::redirect_stream);
l.set_stdin_behavior(bp::redirect_stream);
l.set_merge_out_err(true);
bp::child c = l.start(cl);
bp::pistream& is = c.get_stdout();
string result;
string line;
while (std::getline(is, line) && !_isStopped)
{
result += line;
}
c.wait();
[...]
如果我没记错的话,没有重定向,stdout将一事无成。如果您想要获得整个输出,那么等待进程结束是一个很好的做法
编辑:
我使用的Linux可能是旧版本的boost.process。我意识到您的代码与我给您的代码片段相似。c.wait()可能是键
编辑:Boost.process 0.1:-)如果迁移到“最新”的Boost.process不是问题(您肯定知道,此库有几个变体),您可以使用以下()
可能不是主要问题,但是流的输出应该以二进制模式打开。另外:
streamcopy
可以简化为out Good call on input.rdbuf()。在我写streamcopy之前,我实际上是在使用它来查看引擎盖下发生了什么。
[...]
bp::command_line cl(_commandLine);
bp::launcher l;
l.set_stdout_behavior(bp::redirect_stream);
l.set_stdin_behavior(bp::redirect_stream);
l.set_merge_out_err(true);
bp::child c = l.start(cl);
bp::pistream& is = c.get_stdout();
string result;
string line;
while (std::getline(is, line) && !_isStopped)
{
result += line;
}
c.wait();
[...]
file_descriptor_sink sink("stdout.txt");
execute(
run_exe("test.exe"),
bind_stdout(sink)
);