鎖定功能
此示例演示了 lockf 函式(POSIX XSI)的用法。
筆記:
- 僅支援獨佔鎖。
- 可以應用於位元組範圍,可選擇在將來附加資料時自動擴充套件(由 len引數控制,並通過lseek函式設定位置)。
- 鎖定在第一次關閉時由檔案的任何檔案描述符的鎖定過程釋放,或者在程序終止時釋放。
- fcntl和- lockf鎖之間的相互作用是未指定的。在 Linux 上,- lockf是 POSIX 記錄鎖的包裝器。
#include <stdlib.h>  /* for exit() */
#include <stdio.h>   /* for perror() */
#include <unistd.h>  /* for lockf(), lseek() */
#include <fcntl.h>   /* for open() */
int main(int argc, char **argv) {
    /* open file
     * we need O_RDWR for lockf */
    int fd = open(argv[1], O_RDWR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }
    /* set current position to byte 10 */
    if (lseek(fd, 10, SEEK_SET) == -1) {
        perror("lseek");
        exit(EXIT_FAILURE);
    }
    /* acquire exclusive lock for bytes in range [10; 15)
     * F_LOCK specifies blocking mode */
    if (lockf(fd, F_LOCK, 5) == -1) {
        perror("lockf(LOCK)");
        exit(EXIT_FAILURE);
    }
    /* release lock for bytes in range [10; 15) */
    if (lockf(fd, F_ULOCK, 5) == -1) {
        perror("lockf(ULOCK)");
        exit(EXIT_FAILURE);
    }
    return EXIT_SUCCESS;
}