第五节 文件锁(File lock)

第五节 文件锁(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.

当我们打算在许多进程中锁住一个文件的时候,我们可以调用apr_file_lock()。在历史上,在Unix中关于文件锁有几种争论,即使这样文件锁也是相当有用的。APR的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.

apr_file_lock()有两个参数,一个是apr_file_t对象,另一个是一个标志位我们可以通过他指定锁的类型。锁的类型有APR_FLOCK_SHARED和APR_FLOCK_EXCLUSIVE,我们可以在前面使用这样就成为一个读锁,在后面使用就成为一个写锁。解锁一个文件我们可以调用apr_file_unlock(),或者调用apr_file_close()来强制解锁,具体使用方法可以参照flock-sample.c文件。

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.

另外,我们可以使用APR_FLOCK_NONBLOCK标志位,没有使用APR_FLOCK_NONBLOCK标志位时,调用apr_file_lock()将被堵塞。使用APR_FLOCK_NONBLOCK标志位时,如果apr_file_lock()不能够锁一个文件,他将返回一个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.

我们应该使用APR_SUCCESS和apr_file_lock()的返回值进行毕竟奥,如果返回值为APR_SUCCESS则说明文件锁设置成功,否则说明文件锁设置失败。