flockfile(3S) flockfile(3S)
flockfile, ftrylockfile, funlockfile - stdio synchronization functions
#include <stdio.h>
void flockfile (FILE *file);
int ftrylockfile (FILE *file);
void funlockfile (FILE *file);
flockfile, ftrylockfile, and funlockfile provide for explicit locking and
unlocking of stdio streams. They may be used by a thread to delineate a
sequence of I/O statements to be executed as a critical section.
flockfile is used by a thread to acquire exclusive use of file.
ftrylockfile is used by a thread to acquire exclusive use of file if it
is available; ftrylockfile is a nonblocking version of flockfile.
ftrylockfile returns zero if it successfully acquires the lock, otherwise
a nonzero value is returned.
funlockfile is used to give up the exclusive control granted to the
thread.
Logically, there is a lock count associated with file. The count is
implicitly initialized to 0 when the file is opened. file is unlocked
when the count is 0. When the count is positive a single thread holds
the lock. Each call to flockfile (or successful call to ftrylockfile)
increments the lock count while each call to funlockfile decrements the
lock count. When the lock count is non-zero, threads not holding the
lock on file that call flockfile will suspend and wait for the count to
return to 0. The thread holding the lock on file does not suspend itself
on multiple calls to flockfile, allowing for the nesting of matching
calls to flockfile (or successful calls to ftrylockfile) and funlockfile.
All functions in stdio use these functions to guarantee reentrancy. All
reentrant macros behave as if they are surrounded by calls to flockfile
and funlockfile.
The feature test macro _SGI_REENTRANT_FUNCTIONS should be defined to make
these functions visible.
The semantics of flockfile, ftrylockfile, and funlockfile are undefined
if file is not a valid (FILE *) object. Calling funlockfile without
previously calling flockfile (or successfully calling ftrylockfile)
results in indeterminate behavior.
Page 1
flockfile(3S) flockfile(3S)
Here is a code fragment that uses these functions to guarantee that the
output will be printed without being interspersed with output from other
threads.
#include <stdio.h>
flockfile(stdout);
putchar_unlocked('1');
putchar_unlocked('\n');
printf("Line 2\n");
funlockfile(stdout);
intro(3), getctdio(3S).
PPPPaaaaggggeeee 2222 [ Back ]
|