POSIX 記錄鎖(fcntl)

此示例演示了由 fcntl 函式(POSIX 基本標準) 提供的 POSIX 記錄鎖(也稱為與程序相關的鎖)的用法

筆記:

  • 支援獨佔和共享鎖。
  • 可以應用於位元組範圍,可選擇在將來追加資料時自動擴充套件(由 struct flock 控制)。
  • 鎖定在第一次關閉時由檔案的任何檔案描述符的鎖定過程釋放,或者在程序終止時釋放。
#include <stdlib.h>  /* for exit() */
#include <stdio.h>   /* for perror() */
#include <string.h>  /* for memset() */
#include <unistd.h>  /* for close() */
#include <fcntl.h>   /* for open(), fcntl() */

int main(int argc, char **argv) {
    /* open file
     * we need O_RDWR for F_SETLK */
    int fd = open(argv[1], O_RDWR);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    struct flock fl;
    memset(&fl, 0, sizeof(fl));

    /* lock entire file */
    fl.l_type = F_RDLCK;    /* F_RDLCK is shared lock */
    fl.l_whence = SEEK_SET; /* offset base is start of the file */
    fl.l_start = 0;         /* starting offset is zero */
    fl.l_len = 0;           /* len is zero, which is a special value
                               representing end of file (no matter
                               how large the file grows in future) */

    /* F_SETLKW specifies blocking mode */
    if (fcntl(fd, F_SETLKW, &fl) == -1) {
        perror("fcntl(F_SETLKW)");
        exit(EXIT_FAILURE);
    }

    /* atomically upgrade shared lock to exclusive lock, but only
     * for bytes in range [10; 15)
     *
     * after this call, the process will hold three lock regions:
     *   [0; 10)        - shared lock
     *   [10; 15)       - exclusive lock
     *   [15; SEEK_END) - shared lock
     */
    fl.l_type = F_WRLCK;    /* F_WRLCK is exclusive lock */
    fl.l_whence = SEEK_SET;
    fl.l_start = 10;
    fl.l_len= 5;

    /* F_SETLKW specifies non-blocking mode */
    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl(F_SETLK)");
        exit(EXIT_FAILURE);
    }

    /* release lock for bytes in range [10; 15) */
    fl.l_type = F_UNLCK;

    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl(F_SETLK)");
        exit(EXIT_FAILURE);
    }

    /* close file and release locks for all regions
     * note that locks are released when process calls close() on any
     * descriptor for a lock file */
    close(fd);

    return EXIT_SUCCESS;
}