exit() from child and status in parent wait()

Chris Torek chris at umcp-cs.UUCP
Sat Apr 20 18:44:14 AEST 1985


This probably belongs in net.unix, but . . .

Anyway, the reason you are getting strange exit stati is that your
code is wrong.  "wait" wants a pointer, not a value.

If you are running 4BSD, there is a nice header file (in different
places in 4.1 and 4.2, grr) that defines exactly what wait() fills
in; for other systems, you just have to use an "int *" and pick out
the fields yourself.  The following code forks and picks up the
return status, handing errors that might crop up too:

#include <sys/types.h>
#include <sys/wait.h>		/* <wait.h> in 4.1 */

f()
{
	register int pid, w;
	union wait status;	/* wait gives us back one of these, */
				/* but can use "int" if you have to */

	if ((pid = fork()) < 0) {
		/* probably out of processes */
		/* try to do something about it here */
		return (-1);
	}
	if (pid == 0) {		/* child */
		/* do exec()y stuff here */
		_exit(16);	/* exit() flushes stdio buffers,
				   which can print stuff twice */
		/* NOTREACHED */
	}
	while ((w = wait (&status)) != pid && w > 0)
		;
	if (w <= 0) {		/* catastrophe? */
		/* probably a program bug */
		/* gripe, perhaps, here */
		return (-1);
	}
	/*
	 * Now have status.w_retcode, which is exit code;
	 * status.w_termsig, which is signal (if any)
	 * that terminated proc; and status.w_coredump,
	 * which is true iff the process left us a core
	 * file.
	 */
	/*
	 * Alternatively, "status" can be an integer, in
	 * which case the low 7 bits are the signal, the
	 * eight bit the core-dump flag, and the next eight
	 * bits the exit code.
	 */
	/* do something here based on exit code */
}

Note that if you are implementing a server which will be running as
root, the only reason fork() would fail is if the proc table is full,
so forks should be retried if necessary and practical.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 4251)
UUCP:	{seismo,allegra,brl-bmd}!umcp-cs!chris
CSNet:	chris at umcp-cs		ARPA:	chris at maryland



More information about the Comp.lang.c mailing list