clinuxpopenfclosepclose

Is using fclose() on a pipe opened with popen() a serious bug?


Some months ago I wrote a CGI application for Linux that uses popen() to read the output of a command, and then I close the pipe with fclose().

Now, I read that to close pipes, one needs to use pclose().

The manual says:

The return value from popen() is a normal standard I/O stream in all respects save that it must be closed with pclose() rather than fclose(3).

My code is like this:

if ((NULL != (f = popen(command.value, "r")))) {
    //do something
    fclose(f);
}

My question is:

Does my mistake have a security concern if program is currently in production? In tests, it does not any problem. Is it really needed to patch it using pclose() instead of fclose()? Note: I only open the PIPE one time in the program.

Today, in my local home I do some tests and fclose() or pclose() do not return EOF indicating failure.


Solution

  • If you use fclose() on the pipe, you will have file descriptor leaks, since fclose() will not free the file pointer in the kernel (which is created when you create the pipe since it's a file).

    While your testing so far hasn't shown any problem, run your program 3,000 times (or how ever many file descriptors are allowed, upwards of an int I think) and watch when you no longer are able to create pipes.