【问题标题】:fcntl F_GETLK always returns F_UNLCKfcntl F_GETLK 总是返回 F_UNLCK
【发布时间】:2017-08-10 15:01:15
【问题描述】:

我试图理解 C 中的 POSIX 文件区域锁。下面的程序非常简单,将锁设置为 F_WRLCK,然后获取锁。打开/设置锁时没有错误。不幸的是,它总是返回 F_UNLCK。错误在哪里?有没有可能在 OSX 上不能正常工作?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
void printLockType(int lock) {
    if ( lock == F_RDLCK ) {
            printf("readlock %i \n", lock);
    }else if ( lock == F_WRLCK ) {
            printf("writelock %i \n", lock);
    }else if ( lock == F_UNLCK ) {
            printf("unlock %i \n", lock);
    } else {
            printf("other %i\n", lock);
    }
} 
int main(int argc, char *argv[])
{    
    int fd;
    struct flock fl ,fl2;

    fl2.l_type   = F_RDLCK;  /* read/write lock */
    fl2.l_whence = 0; /* beginning of file */
    fl2.l_start  = 0;        /* offset from l_whence */
    fl2.l_len    = 100;        /* length, 0 = to EOF */
    fl2.l_pid    = getpid();

    fl.l_type   = F_WRLCK;  /* read/write lock */
    fl.l_whence = 0; /* beginning of file */
    fl.l_start  = 0;        /* offset from l_whence */
    fl.l_len    = 1000;        /* length, 0 = to EOF */
    fl.l_pid    = getpid();

    if ((fd = open("xxx", O_RDWR)) == -1) {
        perror("open");
        exit(1);
    }


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

    if(fcntl(fd, F_GETLK, &fl2) == -1) {
        printf("%s \n", strerror(errno));
    } else {
        printLockType(fl2.l_type);
    }

    return 0;
}

【问题讨论】:

  • 澄清一下:您所说的“锁”不是 C 的一部分,而是由 the POSIX standard 定义的。

标签: c macos file-locking fcntl


【解决方案1】:

您误解了F_GETLK 查询。当没有阻止调用进程在给定位置放置给定类型的锁时,它返回F_UNLCK

由于调用进程是创建这些现有锁的那个,它也可以创建这个新锁。


Mac OS X manuals

 F_GETLK 

获取第一个阻塞第三个参数 arg 指向的锁描述的锁, 作为指向结构群的指针(见上文)。检索到的信息会覆盖 在flock结构中传递给fcntl的信息。 如果没有找到锁会阻止 从创建这个锁开始,这个函数调用保持结构不变,除了 对于设置为F_UNLCK的锁类型。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    相关资源
    最近更新 更多