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
该文件已被锁
网友评论