首页 > 解决方案 > 从 C 程序到 Gnuplot 的问题管道数据

问题描述

下午好。我是物理化学本科生,编程经验很少。我正在尝试编写一个程序来使用蒙特卡洛方法获得玻尔兹曼分布。总之,对于“for”循环的每次迭代,我的程序都会生成一个矩阵,其中包含能量的量化值以及占据每个级别的粒子数,然后将这些值写入名为“plot.dat”的文件中,其中第一列的能量(绘制为“x”)和第二列的粒子数(绘制为“y”)。写入文件时,程序请求 gnuplot 使用新值重新绘制图形(之前在开始时分别使用 10 和 999 作为 'x' 和 'y' 的初始值绘制),所以每次迭代完成时我都可以获得物理系统状态的图形输出(也就是说,'plot.dat'的“实时图”,每次文件更改时都会更新)。该程序几乎像预期的那样工作,但大约每 20-30 次迭代,gnuplot 挂起大约 10 秒,并在命令提示符中出现:

gnuplot> plot "auxiliar.dat"
                            ^
line 0: x range is invalid

line 0: warning: Skipping data file with no valid points

然后,程序继续正常运行,gnuplot 更新每次迭代的绘图,直到它再次挂起。我不知道到底发生了什么,但我怀疑 gnuplot 在程序更新它时会尝试读取 plot.dat 文件,因此它失败了。这是令人不安的代码的一部分:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    FILE *plot;
    FILE *pipe = popen("gnuplot -persist" , "wt");
    plot=fopen("plot.dat", "wt");
    fprintf(plot, "10 999\n");
    fclose (plot);
    fprintf(pipe, "plot %plot.dat%c\n", '"', '"');

    int iteration, part1, part2, iteration_msg;
    for (iteration = 0; iteration < 110000; iteration++)
    {
      /* Code of Monte Carlo method here */

      /* Update plot.dat with the new values */
      fprintf(plot, "%d %d\n", plotdata[fila][1],plotdata[fila][0]);
      fclose (plot);

      /*Replot plot.dat in gnu after it's updated*/
      fprintf(pipe, "replot\n");

     }

fclose(pipe);
return 0;
}

你能帮我解决这个问题吗?先感谢您。注意:我在 Windows 中工作。

标签: cpipegnuplot

解决方案


我已经设法解决了每次迭代后清除管道缓冲区的问题:

fflush(pipe);

推荐阅读