flock.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define _FILE_NAME_ "/home/itheima/temp.lock"
int main()
{
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_WRLOCK;
lk.l_whence=SEEK_SET;
lk.l_start=0;
lk.l_len=0;
if(fcntl(fd,F_SETLK,&lk)<0){
perror("get lock err);
exit(1);
}
while(1){
printf("xxx\n");
sleep(1);
}
return 0;
}
本文介绍了一个使用 C 语言实现的简单文件锁程序。该程序通过 fcntl 函数为指定文件设置写锁,并进入无限循环输出状态,展示了如何利用文件锁防止多个进程同时访问同一资源。
699

被折叠的 条评论
为什么被折叠?



