[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

原文地址:https://www.cnblogs.com/co1d7urt/p/2728682.html