Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use fclose to pipe of popen is a serious bug?

Some months ago I write 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 for close pipes is needs 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:

My mistake have a security concern? It program is currently in production. In tests it not do anything problem. Is really needed, patch it using pclose() instead fclose() ? Note: I only open the PIPE one time in the program.

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

like image 401
carlos Avatar asked Aug 19 '13 16:08

carlos


2 Answers

According to this thread, using fclose instead of pclose means that the process at the other end of the pipe doesn't get reaped, so it stays zombied.

like image 159
Chris Jester-Young Avatar answered Oct 02 '22 18:10

Chris Jester-Young


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 its a file).

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

like image 45
Magn3s1um Avatar answered Oct 02 '22 18:10

Magn3s1um