zoukankan      html  css  js  c++  java
  • [linux c]file lock

    #include <unistd.h>
    #include <stdio.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    const char *file="locktest";
    int main(void)
    {
        int file_res;
        file_res=open(file,O_RDWR|O_CREAT|O_EXCL,0444);
        if(file_res == -1)
        {
            printf("create file failed with error %d\n",errno);
        }
        return 0;
    }

    编译运行上面的程序,第一次运行正常,第二次则会提示错误信息。

    怎样在使用时锁住文件,不使用时解锁文件呢?

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdio.h>
    
    const char *file="locktest";
    int main(void)
    {
        int file_res;
        int num=10;
        while(num--)
        {
            file_res = open(file,O_CREAT|O_RDWR|O_EXCL,0444);
            if(file_res == -1)
            {
                printf("%d lock file\n",getpid());
                sleep(2);
            }
            else
            {
                printf("%d not lock\n",getpid());
                sleep(1);
                (void)close(file_res);
                (void)unlink(file);
                sleep(2);
            }
        }
        return 0;
    }

    编译上面的程序

    gcc -o filelock2 filelock2.c

    删除先前第一个创建的文件locktest

    运行 ./filelock2 & ./filelock2

    会看到交替出现

    lock file

    not lock

  • 相关阅读:
    全局变量引用与声明
    Oracle基础~dg原理
    Oracle基础~dg管理
    Oracle基础~rman克隆
    oracle基础~rman恢复篇
    oracle基础~linux整体性能优化
    oracle基础~报错汇总与解决办法
    oracle基础~用户和权限
    oracle基础~rac-asm
    oracle基础~awr报告
  • 原文地址:https://www.cnblogs.com/co1d7urt/p/2728682.html
Copyright © 2011-2022 走看看