1

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?

user1978011
  • 3,419
  • 25
  • 38

2 Answers2

3

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.

Community
  • 1
  • 1
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
0

I'm not sure what kind of answer you imagine you could get to these questions, but…

So I wonder, what is going wrong when closing a pipe created by popen with fclose instead of pclose?

What's going wrong is the programmer is not adhering to the design contract of the popen API. This results in undefined behavior. Exactly what behavior you get is an implementation detail. Literally, you can't know what might go wrong except by analyzing the implementation of the C library you're using.

And why was this working on linux, but not OSX/BSD?

Because undefined behavior can include fclose apparently working like pclose on a file pointer returned by popen. Or it can include it not working in whatever way you observed. And because the implementations differ in innumerable ways.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154