美文网首页
c语言实现文件锁

c语言实现文件锁

作者: 一路向后 | 来源:发表于2021-08-04 21:07 被阅读0次

1.源码实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
    struct flock lock = {0};
    int fd;
    int res;

    umask(0000);

    if((fd=open("a.txt", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) == -1)
    {
        printf("file open failed\n");
        return -1;
    }

    //判断是否有锁
    res = fcntl(fd, F_GETLK, &lock);
    if(res == -1)
    {
        printf("判断是否有锁失败!\n");
        close(fd);
        return -1;
    }

    if(lock.l_type != F_UNLCK)
    {
        printf("该文件已被锁\n");
        close(fd);

        return 0;
    }

    memset(&lock, 0x00, sizeof(lock));

    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 10;
    lock.l_type = F_WRLCK;

    //上锁
    res = fcntl(fd, F_SETLK, &lock);
    if(res == -1)
    {
        printf("上锁失败\n");
        close(fd);
        return -1;
    }

    sleep(20);

#if 0
    //解锁
    lock.l_type = F_UNLCK;
    res = fcntl(fd, F_SETLK, &lock);
    if(res == -1)
    {
        printf("解锁失败\n");
        close(fd);
        return -1;
    }
#endif

    close(fd);

    return 0;
}

2.编译源码

$ gcc -o test1 test.c
$ gcc -o test2 test.c

3.运行及其结果

$ ./test1
$ ./test2
该文件已被锁

相关文章

网友评论

      本文标题:c语言实现文件锁

      本文链接:https://www.haomeiwen.com/subject/cjcpvltx.html