Discussion:
pclose vs. fclose
(too old to reply)
Michel Bardiaux
2006-05-17 09:06:20 UTC
Permalink
I use wrapper structs around FILE*. These structs have a finalizer
(called by my own garbage collector). The finalizer has to call fclose.
*BUT* if the FILE* comes from a popen, it should be pclose.
Unfortunately I was not able to find a way of knowing whether a FILE*
comes from an fopen or popen. Is there one or do I need my own flag?

TIA,
--
Michel Bardiaux
R&D Director
T +32 [0] 2 790 29 41
F +32 [0] 2 790 29 02
E mailto:***@mediaxim.be

Mediaxim NV/SA
Vorstlaan 191 Boulevard du Souverain
Brussel 1160 Bruxelles
http://www.mediaxim.com/
Steve Kirkendall
2006-05-17 16:52:56 UTC
Permalink
Post by Michel Bardiaux
I use wrapper structs around FILE*. These structs have a finalizer
(called by my own garbage collector). The finalizer has to call fclose.
*BUT* if the FILE* comes from a popen, it should be pclose.
Unfortunately I was not able to find a way of knowing whether a FILE*
comes from an fopen or popen. Is there one or do I need my own flag?
The FILE struct is officially an opaque struct, so you shouldn't try
to examine the fields in it directly. I think your best bet is check
whether the FILE's file descriptor is a pipe. The following UNTESTED
code should be about right...

#include <stdio.h>
#include <sys/stat.h>

int finalizefp(FILE *fp)
{
struct stat st;

if (fstat(fileno(fp), &st) < 0)
return -1; /* something munged the buffer? */
else if (S_ISFIFO(st.st_mode))
return pclose(fp);
else
return fclose(fp);
}
Paul Pluzhnikov
2006-05-17 17:45:35 UTC
Permalink
Post by Steve Kirkendall
I think your best bet is check
whether the FILE's file descriptor is a pipe.
This will fail (as in will call pclose() when fclose() should
have been called) if one fopen()s a named pipe, or a "regular" pipe
(possible via /proc/self/fd/fdN or via fdopen()).

Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.
Loading...