• linux文件锁的使用


          在Linux应用编程中,有时我们会需要多个进程访问同一个资源,这时如果不加以保护,就会造成多进程对同一个资源的竞争。在多线程编程时,我们一般习惯用的是互斥锁,达到保护全局变量的目的。但在多进程的时候,我们没法使用互斥锁,那该怎么办呢?其实Linux在读写文件时,自带一种对文件锁的功能。我们可以利用这个文件锁的特性来保护可能存在竞争的资源。Linux文件锁的封装代码如下:

    #include
    #include
    #include
    #include
    #include
    #include

    #define LOCK_FILE_NAME   "lock_file_name"

    int LockInit(void)
    {
        int fd;
        fd = open(LOCK_FILE_NAME, O_RDWR|O_CREAT|O_TRUNC, 0777);
        if(fd < 0){
            printf("open Lock file fail\n");
        }
        return fd;
    }

    int Lock(int fd, unsigned int timeout)
    {
        struct flock lock = {0};
        int ret;
        unsigned int i;
        if(timeout == 0xFFFFFFFF){
            while(1){
                fcntl(fd, F_GETLK, &lock);
                if(lock.l_type == F_UNLCK){
                    break;    
                }
                usleep(5);
            }
        }else if(timeout == 0){
            fcntl(fd, F_GETLK, &lock);
            if(lock.l_type != F_UNLCK){
                printf("Get Lock fail");
                return -1;    
            }
        }else{
            for(i = 0; i < timeout; i++){
                fcntl(fd, F_GETLK, &lock);
                if(lock.l_type == F_UNLCK){
                    break;    
                }
                usleep(1000);
            }
            if(timeout == i){
                fcntl(fd, F_GETLK, &lock);
                if(lock.l_type != F_UNLCK){
                    printf("Get Lock time out\n");
                    return -1;
                }
            }
        }
        memset((void*)&lock, 0, sizeof(struct flock lock));
        lock.l_type = F_WRLCK;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_whence = SEEK_SET;
        ret = fcntl(fd, F_SETLKW, &lock);
        if(ret < 0){
            printf(lock error\n);
            return -1;
        }
        return 0;
    }

    int UnLock(int fd)
    {
        struct flock lock = {0};
        int ret;
        lock.l_type = F_UNLCK;
        lock.l_start = 0;
        lock.l_len = 0;
        lock.l_whence = SEEK_SET;
        ret = fcntl(fd, F_SETLKW, &lock);
        if(ret < 0){
            printf(unlock error\n);
            return -1;
        }
        return 0;
    }

    void main(void)
    {
        int lockfd;
        lockfd = LockInit();
        Lock(lockfd, 0xFFFFFFFF);
        printf("pid = %d\n",getpid());
        UnLock(lockfd);
        
    }

  • 相关阅读:
    UE蓝图 函数调用(CallFunction)节点和源码
    你用过哪些设计模式(一)?
    .net在使用存储过程中IN参数的拼接方案,使用Join()方法
    『现学现忘』Git基础 — 17、Commit对象
    nginx(五十三)nginx中使用的PCRE正则
    大数据业务场景
    Nginx 配置根据路径转发
    如何使用数据选择器配置日期筛选框?
    全网最全的AItium Designer 16下载资源与安装步骤
    100+Python挑战性编程练习系列 -- day 22
  • 原文地址:https://blog.csdn.net/langaopeng/article/details/125906796