Next: , Previous: Threads and Fork, Up: POSIX Threads


34.11 Streams and Fork

The GNU standard I/O library has an internal mutex which guards the internal linked list of all standard C FILE objects. This mutex is properly taken care of during fork so that the child receives an intact copy of the list. This allows the fopen function, and related stream-creating functions, to work correctly in the child process, since these functions need to insert into the list.

However, the individual stream locks are not completely taken care of. Thus unless the multithreaded application takes special precautions in its use of fork, the child process might not be able to safely use the streams that it inherited from the parent. In general, for any given open stream in the parent that is to be used by the child process, the application must ensure that that stream is not in use by another thread when fork is called. Otherwise an inconsistent copy of the stream object be produced. An easy way to ensure this is to use flockfile to lock the stream prior to calling fork and then unlock it with funlockfile inside the parent process, provided that the parent's threads properly honor these locks. Nothing special needs to be done in the child process, since the library internally resets all stream locks.

Note that the stream locks are not shared between the parent and child. For example, even if you ensure that, say, the stream stdout is properly treated and can be safely used in the child, the stream locks do not provide an exclusion mechanism between the parent and child. If both processes write to stdout, strangely interleaved output may result regardless of the explicit use of flockfile or implicit locks.

Also note that these provisions are a GNU extension; other systems might not provide any way for streams to be used in the child of a multithreaded process. POSIX requires that such a child process confines itself to calling only asynchronous safe functions, which excludes much of the library, including standard I/O.