我可以在不关闭文件描述符的情况下打开多个popen吗?

时间:2013-12-06 14:08:31

标签: c linux

我可以使用相同的文件描述符,对于多个popen,而不关闭它,在调用下一个popen之前,在同一个函数中? 从长远来看,任何运行时错误的内存泄漏是什么? e.g。

    fun()
    { FILE *fd  = popen (some_command, "r");
      fd = popen (another_command, "r");
      fd = popen (another_command, "r");
      ... and so on..
      fclose(fd);   //at the end of the program 
    } 

1 个答案:

答案 0 :(得分:3)

不要那样做。您丢失了之前FILE*次呼叫返回的popen,因此您将无法pclose()这些呼叫。因此,这会造成资源泄漏,内存不会被释放,并且您可能无法终止已启动的进程。

另请注意,您应拨打pclose()而不是fclose()