linuxmacospopenfclose

What is going on when fclose on FILE created with popen?


I just had to track down a very annoying bug where somebody used popen to open a pipe but closed the C FILE with fclose instead of pclose. On Linux this was no problem, but later this program was compiled on a OSX and things got awry.

So I wonder, what is going wrong when closing a pipe created by popen with fclose instead of pclose? And why was this working on linux, but not OSX/BSD?


Solution

  • It might only appear to work with Linux, e.g., you did not notice the problem. These questions list a few of the ways your program might malfunction (on a variety of platforms) when using fclose where pclose is needed:

    Those have several comments regarding the bad things that can happen (e.g., zombie processes) from not closing the pipe properly. In some cases, your program may open a pipe once, and then fail to open a pipe a second time.