【问题标题】:C File Locking behavior on windows and LinuxWindows 和 Linux 上的 C 文件锁定行为
【发布时间】:2011-08-13 15:08:30
【问题描述】:

我正在研究以下示例以了解 Windows 和 linux 上的文件锁定。程序 1 正在使用 gcc 在 windows 和 linux 上运行。

但第二个仅适用于 Linux。特别是 windows GCC 中的问题来自结构群声明。我不知道我是否在这里遗漏了任何东西。此外,即使在我关闭并取消链接第一个示例中的文件以进行下一次运行后,文件也没有解锁。

程序 1:使用 GCC 在 Windows 上工作

来源:http://www.c.happycodings.com/Gnu-Linux/code9.html

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int main()

{
    if((fd = open("locked.file", O_RDWR|O_CREAT|O_EXCL, 0444)) == -1) 
    {
        printf("[%d]: Error - file already locked ...\n", getpid());
    } 
    else 
    {
    printf("[%d]: Now I am the only one with access :-)\n", getpid());
    close(fd);
    unlink("locked.file");
}

程序 2:使用 GCC 在 Linux 上工作

来源:http://beej.us/guide/bgipc/output/html/multipage/flocking.html

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
                    /* l_type   l_whence  l_start  l_len  l_pid   */
    struct flock fl = {F_WRLCK, SEEK_SET,   0,      0,     0 };
    int fd;
    fl.l_pid = getpid();
    if (argc > 1) 
        fl.l_type = F_RDLCK;
    if ((fd = open("lockdemo.c", O_RDWR)) == -1) {
        perror("open");
        exit(1);
    }
    printf("Press <RETURN> to try to get lock: ");
    getchar();
    printf("Trying to get lock...");
    if (fcntl(fd, F_SETLKW, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }
    printf("got lock\n");
    printf("Press <RETURN> to release lock: ");
    getchar();
    fl.l_type = F_UNLCK;  /* set to unlock same region */
    if (fcntl(fd, F_SETLK, &fl) == -1) {
        perror("fcntl");
        exit(1);
    }
    printf("Unlocked.\n");
    close(fd);
    return 0;
}

您能否提供帮助,并在可能的情况下提供这些场景中可移植代码的指南?

【问题讨论】:

  • 我担心您正在冒险进入固有的不可移植性领域。如果你使用 cygwin,它会模拟 unix API,否则它在 windows 上不存在,你要么需要编写两个版本,要么使用一些已经将它包装在可移植接口中的库。
  • 谢谢 Jan. 是的。我也在尝试使用cygwin。但是您是否确认我们不能在 Windows 和 Linux 上使用 fcntl 锁定文件?
  • 好吧,windows,本机 (VisualC++) 环境,根本没有记录 fcntl。但是尝试使用 mingw gcc 附带的 msys 库进行编译;那里似乎有一些模拟。
  • 如果您描述问题会有所帮助

标签: c windows linux file locking


【解决方案1】:

我会特别研究XPDEV 的文件包装方法...它们实现了合理的跨平台锁定。

【讨论】:

    【解决方案2】:

    使用 C Runtime LIbrary 可能很难通过这种操作获得 protabiltiy。你真的需要为这种事情使用操作系统特定的代码。

    但是,您可以通过检查和理解底层 C 运行时库实现来实现它。 GCC 运行时和 Microsoft 运行时的源代码都随这些工具一起提供。去看看他们是怎么实现的。

    请注意,在 Windows 上,您可以将 CRT 文件 I/O API 与 Windows 句柄一起使用。去看看源码吧。

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2014-07-08
      • 2023-02-04
      • 2020-01-12
      • 2013-03-12
      相关资源
      最近更新 更多