linuxc编程——文件锁
文件锁
在多个进程同时操作同一份文件的过程中,很容易导致文件中的数据混乱,需要锁操作来保证数据的完整性,这里介绍的针对文件的锁,称之为“文件锁”-flock。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define _FILE_NAME_ "/home/youName/Downloads/temp.lock"
int main(int argc, char const *argv[])
{
int fd = open(_FILE_NAME_,O_RDWR|O_CREAT,0666);
if(fd<0){
perror("open err");
return -1;
}
struct flock lk;
lk.l_type = F_WRLCK;
lk.l_whence = SEEK_SET;
lk.l_start = 0;
lk.l_len = 0;
if(fcntl(fd,F_SETLK,&lk)<0){
perror("get lock err");
}
while (1)
{
printf("I am alive!\n");
sleep(1);
}
return 0;
}
启动终端1
./06_flock
I am alive!
I am alive!
I am alive!
I am alive!
I am alive!
I am alive!
I am alive!
启动终端2
get lock err: Resource temporarily unavailable
还没有评论,来说两句吧...