Multithreaded Programming Guide

Choosing the Right Fork

You determine whether fork() has a "fork-all" or a "fork-one" semantic in your application by linking with the appropriate library. Linking with -lthread gives you the "fork-all" semantic for fork(), and linking with -lpthread gives the "fork-one" semantic for fork() (see Figure 7-1 for an explanation of compiling options).

Cautions for Any Fork

Be careful when using global state after a call to any fork() function.

For example, when one thread reads a file serially and another thread in the process successfully calls one of the forks, each process then contains a thread that is reading the file. Because the seek pointer for a file descriptor is shared after a fork(), the thread in the parent gets some data while the thread in the child gets the other. This introduces gaps in the sequential read accesses.