繁体   English   中英

C windows 和 Linux 上的文件锁定行为

[英]C File Locking behavior on windows and Linux

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

但第二个仅适用于 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;
}

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

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

但是,您可以通过检查和理解底层 C 运行时库实现来实现此功能。 GCC 运行时和 Microsoft 运行时的源代码随工具一起提供。 只需 go 看看它们是如何实现的。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM