Next Previous Contents

6. file lock

When we intend to lock file among processes, we can use apr_file_lock(). Historically, there are several confusions about file lock APIs on Unix. Thus, it is very useful that libapr provides one simple API.

/* excerpted from apr_file_io.h */

APR_DECLARE(apr_status_t) apr_file_lock(apr_file_t *thefile, int type);
APR_DECLARE(apr_status_t) apr_file_unlock(apr_file_t *thefile);

apr_file_lock() has two arguments. One is apr_file_t object. The other is flag, by which we specify the lock type. The lock type is either APR_FLOCK_SHARED or APR_FLOCK_EXCLUSIVE. We can use the former as a readable lock, and the latter as a writable lock. To unlock the file, we call apr_file_unlock(). Or, calling apr_file_close() implicitly does unlock. Take a look at flock-sample.c about the usage.

Additionally, we can use a bitwised-or flag APR_FLOCK_NONBLOCK. Without APR_FLOCK_NONBLOCK flag, calling apr_file_lock() would block. With APR_FLOCK_NONBLOCK, if apr_file_lock() can't lock file, it returns an error code, APR_EAGAIN.

We should compare apr_file_lock() return value with APR_SUCCESS. If the value is APR_SUCCESS, the file was successfully locked. Othewrise, we failed to lock the file.


Next Previous Contents