代码之家  ›  专栏  ›  技术社区  ›  Jeremy Friesner

为什么popen()只工作一次?

  •  4
  • Jeremy Friesner  · 技术社区  · 15 年前

    $ ./a.out 
    Read 66 lines of output from /bin/ps
    Read 0 lines of output from /bin/ps
    Read 0 lines of output from /bin/ps
    Read 0 lines of output from /bin/ps
    Read 0 lines of output from /bin/ps
    

    为什么popen()只在我第一次调用它时读取数据,而随后的传递不返回输出?

    #include <stdio.h>
    
    int main(int argc, char ** argv)
    {
       int i;
       for (i=0; i<5; i++)
       {
          FILE * psAux = popen("/bin/ps ax", "r");
          if (psAux)
          {
             char buf[1024];
             int c = 0;
             while(fgets(buf, sizeof(buf), psAux)) c++;
             printf("Read %i lines of output from /bin/ps\n", c);
             fclose(psAux);
          }
          else printf("Error, popen() failed!\n");
    
          sleep(1);
       }
    }
    
    2 回复  |  直到 15 年前
        1
  •  6
  •   Peter    15 年前

    你应该使用 pclose 而不是 fclose

    F关闭 文件夹 . 将正确关闭管道,以便您可以成功地重新打开它。

        2
  •  2
  •   Community Mohan Dere    9 年前

    看一看 here 为了一个深入的原因 fclose pclose