Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 8.9 Race Conditions 245


8.8 wait3andwait4 Functions


Most UNIX system implementations provide two additional functions:wait3 and
wait4.Historically,these two variants descend from the BSD branch of the UNIX
System. The only featureprovided by these two functions that isn’t provided by the
wait,waitid,andwaitpidfunctions is an additional argument that allows the kernel
to return a summary of the resources used by the terminated process and all its child
processes.
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
pid_t wait3(int *statloc,intoptions,struct rusage *rusage);
pid_t wait4(pid_tpid,int *statloc,intoptions,struct rusage *rusage);
Both return: process ID if OK, 0, or−1 on error

The resource information includes such statistics as the amount of user CPU time,
amount of system CPU time, number of page faults, number of signals received, and the
like. Refer to thegetrusage( 2 )manual page for additional details. (This resource
information differs from the resource limits we described in Section 7.11.) Figure8.11
details the various arguments supported by thewaitfunctions.

FreeBSD Linux Mac OS X Solaris
Function pid options rusage POSIX.1 8.0 3.2.0 10.6.8 10

wait •••••
waitid •• • •••
waitpid •• • ••••
wait3 •• ••••
wait4 ••• ••••

Figure 8.11 Arguments supported bywaitfunctions on various systems

Thewait3function was included in earlier versions of the Single UNIX Specification. In
Version 2, wait3was moved to the legacy category;wait3 was removed from the
specification in Version 3.

8.9 Race Conditions


For our purposes, a race condition occurs when multiple processes aretrying to do
something with shared data and the final outcome depends on the order in which the
processes run. Theforkfunction is a lively breeding ground for race conditions, if any
of the logic after theforkeither explicitly or implicitly depends on whether the parent
or child runs first after thefork.Ingeneral, we cannot predict which process runs first.
Even if we knew which process would run first, what happens after that process starts
running depends on the system load and the kernel’s scheduling algorithm.
Free download pdf