freopen() broken in Fedora 15

Chris Adams cmadams at hiwaay.net
Fri Jun 10 04:07:04 UTC 2011


Once upon a time, Chuck Forsberg WA7KGX N2469R <caf at omen.com> said:
> The standard IO freopen function stopped working on or about
> the time I installed 64 bit Fedora 15 on the omen.com server.
> 
> The attached program is derived from the 1977 Bill Joy version.
> It does not display any text when compiled and run under 64 bit
> F 15 clean install and updated as of today.
> 
> The workaround is to rewrite the program to eliminate the use
> of freopen.

The problem is that file descriptors and file streams are being mixed
(and without proper includes).

> #ifndef	lint
> static char *sccsid = "@(#)head.c	4.1 (Berkeley) 10/1/80";
> #endif
> #include <sys/types.h>
> #include <sys/stat.h>
> #include <stdio.h>
> #include <string.h>
> #include <stdlib.h>

<snip>

> 			close(0);

close() is defined in unistd.h, not included above.  It operates on file
descriptors.

> 			if (freopen(argv[0], "r", stdin) == NULL) {

freopen() operates on file streams.  The underlying library routine will
allocate a file descriptor, but that is transparent to the caller.

Mixing access on descriptors and streams is bad and I believe undefined
behavior, especially closing a descriptor out from under a stream.  It
may have worked before, but that's not guaranteed by anything.

In any case, the close(0) is unnecessary, as the whole point of
freopen() is that it will close the existing stream (and internally-used
descriptor) as necessary (which may or may not be descriptor 0).

In short: the code you sent is broken - fix it.
-- 
Chris Adams <cmadams at hiwaay.net>
Systems and Network Administrator - HiWAAY Internet Services
I don't speak for anybody but myself - that's enough trouble.


More information about the test mailing list