checking return values of close(2)

Bennett Todd -- gaj bet at bent.mc.duke.edu
Sat Oct 20 03:15:27 AEST 1990


Anyone who cares about writing robust programs should be checking the return
values of every system call that can return an error. This can get tedious;
I've seen a solution in other people's programs that I like, and which I've
adopted for my own use.

There is an external "char *" variable "progname", which I initialize to
argv[0] as the first line of executable code in main(). Thereafter, if I
don't want to program any special handling and recovery of an error, but
just print a message and exit, I call a routine whose name is prefixed with
"e". Thus if I call eclose() I don't have to check for an error return; if
anything goes wrong it will end up running

	(void) fprintf(stderr, "%s: close() failed: %s\n", progname,
                                 ((errno == 0)        ? "No error!?" :
	                          ((errno < sys_nerr) ? sys_errlist[errno] :
	                                                "Unknown error")));
	exit(1);

only with the filename included (see below).

I've got routines starting with 'e' for everything that I've needed so far
out of sections 2 and 3 of the UPM; it sure takes the pain out of whipping
out robust utilities. I also have some other goodies tucked in to this
library. Emalloc() overallocates by a fixed amount and inserts a header and
appends a trailer; erealloc()/efree() check the header and trailer,
reporting that the malloc arena has been corrupted if they have been
stomped. Eopen() and efopen() stash a copy of the filename in a table
indexed by the file descriptor; all the routines that take file descriptors
attempt to report the filename by checking that table, and report the file
descriptor number if the filename isn't available. The program size penalty
isn't all that great, the source code doesn't get any more cluttered, and
the resulting programs seem to be more robust in the face of full
filesystems and suchlike.

If anyway wants a copy I'll be glad to email or post my library; it fits
neatly in two mailings/postings, one for libc.h and one for everything else.

-Bennett
bet at orion.mc.duke.edu



More information about the Comp.unix.internals mailing list