c - 为什么 fcntl() 不阻塞 WSL 中的 F_SETLKW?

标签 c linux ubuntu windows-subsystem-for-linux fcntl

我试图找出在 Linux 中锁定文件的不同类型的方法,我刚刚遇到了 fcntl()。

根据手册页,如果文件上持有冲突锁,fcntl() 和 F_SETLKW 应该会阻塞。所以我创建了以下代码片段并在两个终端上运行。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

//lock.c is the file name
void lock() {
    struct flock fl;

    fl.l_type = F_WRLCK;
    fl.l_len = 10;
    fl.l_start = 0;
    fl.l_whence = SEEK_SET;
    fl.l_pid = getpid();

    int fd1 = open("lock.c", O_RDWR);
    printf("Try to set the lock!\n");
    int res = fcntl(fd1, F_SETLKW, &fl);
    printf("Set the lock with status: %d\n", res);

    sleep(20);
}

int main(void)
{
    lock();
}

我的预期结果是第一个进程应该立即打印出两行,而第二个进程应该只打印出第一行并等待第一个进程完成休眠然后打印出第二行。

但事实证明,这两个进程都立即打印出这两行并开始休眠。是我误解了 fcntl() 的工作原理还是代码中存在错误?

$./lock
Try to set the lock!
Set the lock with status: 0

最佳答案

好的,我想我找到了问题所在。我将 WSL 2(昨天更新)与 Windows 10 商店的 Ubuntu 子系统一起使用。而且 fcntl() 在 WSL 中不支持/有错误 F_SETLK,但是。这是相当长一段时间以来的已知问题。

https://github.com/Microsoft/WSL/issues/1927

关于c - 为什么 fcntl() 不阻塞 WSL 中的 F_SETLKW?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59243106/

相关文章:

linux - TSS_WELL_KNOWN_SECRET 的值是多少

python 生成器 int() 的无效文字

c - g_source_set_callback : invalid callback data pointer

ubuntu - 在 ubuntu 21.10 中找不到 gnome-session-wayland

gcc - Ubuntu 12.04LTS安装CASAVA报错

c - 在多线程程序中访问文件指针时出错

c - 我如何理解复杂的函数声明?

c - C 中 SWITCH CASE 中的多个字符

C - 段错误(核心转储),从文件中读取前 N 个字节

c - 编译器标志有什么用?为什么我的代码无法编译?