问题描述
在Windows上,我使用_popen具有以下工作代码,
I have the following working code using _popen, on windows,
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窗口不断弹出,并且没有办法阻止它()因此,我在boost :: process
But the problem with this is that cmd window keeps poping up, and there is no way to prevent that (Link)So, I write the equivalent code in 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);
所以,我的问题是-两个代码段是否等效?如果是这样,为什么第二个不起作用?
So, my question is - are the two code snippets equivalent? And if so, why might the second one not work?
推荐答案
我没有Windows,因此我在Linux机器上对其进行了测试,略有简化:
I don't have windows, so I tested it on my linux box, slightly simplified:
#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
并从简单数据中创建了这张漂亮的图片:
And created this nice image from simplistic data:
在Windows上,利用Boost Filesystem的path
的功能执行路径:
On windows, leverage the power of Boost Filesystem's path
to do the path:
boost::filesystem::path program("C:\\gnuplot\\bin\\gnuplot.exe");
其他说明
如果整个脚本确实是固定的,请考虑使用原始文字:
Other Notes
If the whole script is, indeed, fixed, consider using a raw literal:
m_Write << R"(set term png
set output "Out.png"
plot "Data.txt" using 1:2 notitle)" << std::flush;
m_Write.pipe().close();
这篇关于为何_popen在这里起作用,而boost :: process却不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!