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

时间:2011-04-27 07:21:10

标签: c windows linux file locking

我正在查看以下示例,以了解锁定在Windows和Linux上的文件。程序1正在使用gcc在windows和linux上工作。

但第二个只适用于Linux。特别是winodws 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;
}

请您帮助解决这个问题,如果可能的话,在这些情况下提供可移植代码的指南?

2 个答案:

答案 0 :(得分:1)

使用C Runtime LIbrary进行这种操作可能很难获得稳定性。你真的需要使用特定于操作系统的代码来处理这类事情。

但是,您可以通过检查和理解底层的C运行时库实现来实现这一点。 GCC运行时和Microsofot运行时的源代码都带有工具。只要去看看它们是如何受到重视的。

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

答案 1 :(得分:0)

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

相关问题