*BSD News Article 2369


Return to BSD News archive

Xref: sserve comp.sys.sun.misc:2901 comp.unix.ultrix:12768 comp.unix.bsd:2413
Path: sserve!manuel!munnari.oz.au!uunet!wupost!zaphod.mps.ohio-state.edu!magnus.acs.ohio-state.edu!usenet.ins.cwru.edu!agate!ICSI.Berkeley.EDU!stolcke
From: stolcke@ICSI.Berkeley.EDU (Andreas Stolcke)
Newsgroups: comp.sys.sun.misc,comp.unix.ultrix,comp.unix.bsd
Subject: Beware of fileno()
Date: 24 Jul 1992 00:36:30 GMT
Organization: International Computer Science Institute, Berkeley, CA, U.S.A.
Lines: 29
Distribution: world
Message-ID: <14njaeINNvk@agate.berkeley.edu>
NNTP-Posting-Host: icsib30.icsi.berkeley.edu
Keywords: sunos, ultrix, stdio, fileno, lossage

Hi,

I was just wondering if I am the first one to hit upon this (I suspect not).
I was debugging a program that uses lots of file descriptors, which 
started to elicit Bad file number errors for no obvious reasons.

It turned out, the fileno() macro from stdio.h was to blame.  If you do a

	FILE *stream = fopen(....);
	int d = fileno(stream);

and you have used up all file descriptors up to 127, you're screwed.
This is because fileno() returns a char field in the FILE structure.
On systems like Sun where char is signed this results in a negative
integer file descriptor.  To prevent lossage, one has to use

	(unsigned char)fileno(stream)

or explicitly mask the most significant bits off.
The right solution, of course, would be to define the file number field
as unsigned char to begin with.

SunOS, Ultrix and MIPS RISC/os have the same problem, so I suspect it comes
from BSD.  Why has this never been fixed?

-- 
Andreas Stolcke					stolcke@icsi.berkeley.edu
International Computer Science Institute	stolcke@ucbicsi.bitnet
1947 Center St., Suite 600, Berkeley, CA 94704	(510) 642-4274 ext. 126