#include
#include
#include
#include
int lock_file(int fd,int cmd,int type,off_t offset,int whence,off_t len)
{
struct flock lock;
lock.l_type = type;
lock.l_start = offset;
lock.l_whence = whence;
lock.l_len = len;
return (fcntl(fd,cmd,&lock));
}
int main(int argc,char **argv)
{
int fd;
fd = open("./data",O_WRONLY | O_CREAT,00777); //可以看出现在是写的方式打开文件
pid_t pid;
char buf[100]="wahahah";
char max[100]="xxxxxxx";
if((pid = fork())<0) //开出两个进程去同时对这个文件进行操作
{
printf("fork error\n");
}
else if(pid == 0){
//child 子进程对已用读方式打开的文件进行加写锁,并对其进行写操作
lock_file(fd,F_SETLK,F_WRLCK,0,SEEK_SET,0);
if(write(fd,buf,sizeof(buf))==-1)
{
printf("child write error\n");
}
sleep(10);
printf("start unlock\n");
int n =lock_file(fd,F_SETLK,F_UNLCK,0,SEEK_SET,0); //10秒后对其进行解锁操作
close(fd);
printf("n is %d\n",n);
//unlock_file(fd,F_UNLCK,0,SEEK_SET,0);
}
else{
int par_fd;
par_fd = open("./data",O_RDONLY); //父进程以读的方式打开同一个文件
sleep(1); //保证子进程先于父进程加锁
for(;;)
{
if(lock_file(par_fd,F_SETLK,F_RDLCK,0,SEEK_SET,0) == -1)
{
printf("parent lock error\n"); //会发现,当对该文件进行读操作时,fcntl会出错,并返回-1,没有设置成等待模式
continue;
}
printf("unlock success\n"); //在子进程解锁后父进程读加锁成功
}
//parent
}
return 0;
}