ftrylockfile() — stdio locking

Standards

Standards / Extensions C or C++ Dependencies

Single UNIX Specification, Version 3

both  z/OS V1R8

Format

#define _UNIX03_SOURCE 
#include <stdio.h>

int ftrylockfile(FILE *file);

General description

This function provides explicit application-level locking of stdio (FILE*) objects. The flockfile() family of functions can be used by a thread to delineate a sequence of I/O statements that are executed as a unit.

If the (FILE*) object specified by the ftrylockfile() function is available, ownership is granted to the thread for the (FILE*) object and the internal lock count is increased. If the thread has previously been granted ownership, the internal lock count is increased. If another thread has been granted ownership, ftrylockfile() does not grant ownership to the calling thread and returns a non-zero value. ftrylockfile() is a non-blocking version of flockfile().

The internal lock count allows matching calls to flockfile() (or successful calls to ftrylockfile()) and funlockfile() to be nested.

z/OS® consideration: The flockfile() family of functions acts upon FILE * objects. It is possible to have the same physical file represented by multiple FILE * objects that are not recognized as being equivalent. For example, fopen() opens a file and open() opens the same file, and then fdopen() creates a FILE * object. In this case, locking the first FILE * does not prevent the second FILE * from also being locked and used.

Returned value

The ftrylockfile() function returns zero for success and non-zero to indicate that the lock cannot be acquired.
Error Code
Definition
EBADF
The input (FILE *) object is not valid.
EBUSY
The input (FILE *) object is locked by another thread.
Note: It is the application’s responsibility to prevent deadlock (or looping). For example, deadlock (or looping) may occur if a (FILE *) object is closed, or a thread is terminated, before relinquishing all locked (FILE *) objects.

Related information