The errno variable can get trashed

Kenneth Almquist ka at hou3c.UUCP
Tue Aug 7 01:59:01 AEST 1984


	The global 'errno' variable set by the assembler routines in the
	C library for system-call interface can be garbled before the
	program gets to look at it if a signal arrives and the signal-handling
	routine does another system call (which gets an error).

This is a specific case of a general problem with signal handlers that
modify global or static variables.  For example, a call to malloc in a
signal handler can result in a corrupted free space list.  Radford suggests
that the signal mechanism should save and restore the value of errno, but
the only solution to the general problem is care on the part of the
programmer.

One way to fix Radford's example is to have the alarm routine simply
set a flag for later processing.  The code becomes:

	static int alflag;	/* set when alarm signal received */

	void i() {		/* called on alarm signal */
		alflag++;
	}

	void testalarm() {	/* called from loop in main routine */
		if (alflag) {
			alflag = 0;
			signal(SIGALARM, i);
			alarm(1);
			open(".", 1);		/* this will fail */
		}
	}

Another fix would of course be to have the routine "i" save and restore
the value of errno.
				Kenneth Almquist



More information about the Comp.unix.wizards mailing list