Is using fclose to pipe of popen a serious mistake?

A few months ago, I write a CGI application for Linux that uses popen() to read the output of a command, and then I close the channel with fclose() .

Now I read that using closed pipes requires pclose() .

The manual says:

The return value from popen() is the standard standard input / output stream in all, keeping that it should be closed by pclose() , not fclose(3) .

My code looks like this:

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

My question is:

Is my mistake related to security? This program is currently in production. In tests, this does nothing. Really need to fix it using pclose() instead of fclose() ? Note. I only open PIPE once in the program.

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

+6
source share
3 answers

If you use fclose on the pipe, you will have a file descriptor leak, since fclose will not free the file pointer in the kernel (which is created when the channel is created from the moment it was created).

While your testing has not yet shown any problems, run the program 3,000 times (or how many file descriptors can be resolved), and see when you can no longer create channels.

+5
source

According to this thread , using fclose instead of pclose means that the process at the other end of the pipe does not get reaped, so it remains zombified.

+10
source

I just found out (after 10 years) that I mistakenly used fclose for some popen calls running on a Windows 2008 server. It worked (that is, it didn’t crash), and I still don’t need a return code for these calls.

But I need the return code of the last popen thread, and the closure was done using pclose .

It has a strange effect of returning error code 0 (it is possible that the return code was not previously pclosed ), even if the command failed, creating a very strange error in the code, which could be disastrous because the caller believes that the command worked.

Thus, it is not only a matter of descriptor leakage, it can introduce functional errors into your code (even if the application runs for several seconds and you do not care about the descriptor leakage)

0
source

Source: https://habr.com/ru/post/952045/


All Articles