PreviousNext

The atfork(~) Routine

The atfork( ) routine allows an application or library to ensure predicted behavior when the fork( ) routine is used in a multithreaded environment. Using the fork( ) routine from a threaded application or from an application that uses threaded libraries can result in unpredictable behavior. For example, one thread has a mutex locked, and the state covered by that mutex is inconsistent while another thread calls the fork( ) routine. In the child process, the mutex will be in the locked state, and it cannot be unlocked because only the forking thread exists in the child process. Having the child reinitialize the mutex is unsatisfactory because this approach does not resolve the question of how to correct the inconsistent state in the child.

The atfork( ) routine provides a way for threaded applications or libraries to protect themselves when a fork( ) occurs. The atfork( ) routine allows you to set up routines that will run at the following times:

· Prior to the fork( ) in the parent process

· After the fork( ) in the child process

· After the fork( ) in the parent process

Within these routines, you can ensure that all mutexes are locked prior to the fork( ) and that they are unlocked after the fork( ), thereby protecting any data or resources associated with the mutexes. You can register any number of sets of atfork( ) routines; that is, any number of libraries or user programs can set up atfork( ) routines and they will all execute at fork( ) time.

Note: Using the atfork( ) routine can potentially cause a deadlock if two applications or libraries call into one another using calls that require locking. Specifically, when these component's routines use the atfork( ) routine to run prior to the fork in the parent process, a deadlock may occur when these routines are executing.