为什么_popen在这里工作,但boost :: process不行?

时间:2018-03-27 10:04:02

标签: c++ boost gnuplot popen boost-process

我在Windows上使用_popen有以下工作代码,

m_pGNUPlot = _popen("/gnuplot/bin/gnuplot.exe", "w");
fprintf(m_pGNUPlot, "set term win\n");
fprintf(m_pGNUPlot, "set term pngcairo\n"); 
fprintf(m_pGNUPlot, "plot \"\Data.txt\" using 1:2 notitle\n"); 
fprintf(m_pGNUPlot, "set output \"\Out.png\"\n");
fprintf(m_pGNUPlot, "replot\n");
fflush(m_pGNUPlot);

但问题是cmd窗口不断弹出,而且无法阻止(Link) 所以,我在boost :: process

中编写了等效的代码
bp::pipe m_Write;
bp::environment env = boost::this_process::environment();
m_Plot = new bp::child("/gnuplot/bin/gnuplot.exe", bp::std_in < m_Write, env, boost::process::windows::hide);
m_Write.write("set term win\n", sizeof(char)*14);
m_Write.write("set term pngcairo\n", sizeof(char) * 19);    
m_Write("plot \"\Data.txt\" using 1:2 notitle\n", sizeof(char)*35);
m_Write("set output \"\Out.png\"\n", sizeof(char)*22);
m_Write.write("replot\n", sizeof(char) * 8);

所以,我的问题是 - 两个代码片段是否相同?如果是这样,为什么第二个不起作用?

2 个答案:

答案 0 :(得分:2)

我没有窗户,所以我在我的linux机箱上进行了测试,稍微简化了一下:

#include <boost/process.hpp>
#include <iostream>

namespace bp = boost::process;

int main() {
    bp::opstream m_Write;
    boost::filesystem::path program("/usr/bin/gnuplot");
    bp::child m_Plot(program, bp::std_in = m_Write);

    m_Write << "set term png\n";
    m_Write << "set output \"Out.png\"\n";
    m_Write << "plot \"Data.txt\" using 1:2 notitle\n";
    m_Write.flush();
    m_Write.pipe().close();

    m_Plot.wait();
    std::cout << "Done, exit code: " << m_Plot.exit_code() << "\n";
}

打印:

Done, exit code: 0

并从simplistic data创建了这张漂亮的图片:

在Windows上,利用Boost Filesystem的path的强大功能来执行路径:

boost::filesystem::path program("C:\\gnuplot\\bin\\gnuplot.exe");

其他注释

如果确实修复了整个脚本,请考虑使用原始文字:

m_Write << R"(set term png
    set output "Out.png"
    plot "Data.txt" using 1:2 notitle)" << std::flush;
m_Write.pipe().close();

答案 1 :(得分:1)

是的,谢谢你! Boost功能强大,但缺乏教程和示例使得很难开始使用。

是的,所以我的最终工作代码 -

bp::opstream m_Write; //output stream to pipe   
boost::filesystem::path program("/gnuplot/bin/gnuplot.exe");
m_Plot = new bp::child(program, bp::std_in = m_Write, bp::windows::hide); //this solves the problem with _popen
m_Write << "set term png\n";
m_Write << "set term pngcairo\n"; 
m_Write << "set output \"" + ToPosixPath(sPath) + "\"\n"; //Notice how this works with std::string :)
m_Write << "plot  \"" + CreateTemp(X, Y) + "\" using 1:2 notitle\n";
m_Write << "exit\n";
m_Write.flush();
m_Write.pipe().close();

m_Plot->wait(); //boost doc states "The call to wait is necessary, to obtain it and tell the operating system, that no one is waiting for the process anymore."
delete m_Plot;

有些观点 -

  • 在windows中支持gnuplot.exe本身的管道的exe,而在linux中有两个 - gnuplot.exe和pgnuplot.exe。

  • 确保在GUI中测试脚本,此代码无声地失败!返回码为0。