【问题标题】:fcntl doesn't lock/unlock the files [Unix - C]fcntl 不锁定/解锁文件 [Unix - C]
【发布时间】:2021-08-14 04:05:21
【问题描述】:

我正在尝试使用 fcntl lib(在 UNIX c 编程中)来锁定或解锁文件,但似乎没有锁定,我不知道为什么。我没有收到任何错误,看起来程序在执行锁定但实际上我可以读/写文件并且没有被锁定

    if (enter == 2){
    getchar ();
    int fd;
    struct flock lock;
    char file[20];
    printf ("Enter file name:");
    fgets(file,20,stdin);
    printf ("opening %s\n", file);
    //Open a file descriptor to the file
    fd = open (file, O_RDWR);
    printf ("locking\n");
    //Initialize the flock structure
    memset (&lock, 0, sizeof(lock));
    lock.l_type = F_WRLCK;
    //Place a write lock on the file
    fcntl (fd, F_SETLK, &lock);
    
    printf ("locked; hit Enter to unlock... ");
    //Wait for the user to hit Enter
    getchar ();
    printf ("unlocking\n");
    //Release the lock
    lock.l_type = F_UNLCK;
    fcntl (fd, F_SETLK, &lock);
    close (fd);

【问题讨论】:

  • 锁定只是建议性的。其他进程需要检查文件是否设置了此建议锁。

标签: c unix fcntl


【解决方案1】:

当你没有检查fcntl的结果时,你声称你已经锁定了文件是非常大胆的。

无论如何,这是预期的行为。获得锁所做的只是阻止其他人获得锁。[1]它不会阻止任何人读取或写入文件。


  1. 写锁可防止任何人获得锁,而读锁仅可防止获得写锁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 2021-06-21
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    相关资源
    最近更新 更多