1. Agregue un bloqueo de lectura al archivo
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <sys/file.h>
#include <fcntl.h>
#include <stdlib.h>
int lock_set(int fd,int type)
{
struct flock old_lock,lock;
lock.l_whence =SEEK_SET;
lock.l_start =0;
lock.l_len =0;
lock.l_type =type;
lock.l_pid=-1;
fcntl(fd,F_GETLK,&lock);
if(lock.l_type!=F_UNLCK)
{
if(lock.l_type ==F_RDLCK)
{
printf("read lock already set by %d\n",lock.l_pid);
}
else if (lock.l_type ==F_WRLCK)
{
printf("write lock already set by %D\n",lock.l_pid);
}
}
lock.l_type=type;
if((fcntl(fd,F_SETLKW,&lock))<0)
{
printf("Lock failed:type =%d\n",lock.l_type);
return 1;
}
else
{
switch(lock.l_type)
{
case F_RDLCK :
{
printf("read lock set by %d",getpid());
}
break;
case F_WRLCK :
{
printf("write lock set by %d\n",getpid());
}
break;
case F_UNLCK :
{
printf("Release lock set by %d\n",getpid());
}
break;
default :
break;
}
}
return 0;
}
int main(void)
{
int fd;
fd=open("hello",O_RDWR|O_CREAT,0644);
if(fd<0)
{
printf("Open file error\n");
exit(1);
}
lock_set(fd,F_RDLCK);
getchar();
lock_set(fd,F_UNLCK);
getchar();
close(fd);
exit(0);
}
2. Escribir y bloquear archivos
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/file.h>
#include<fcntl.h>
int lock_set(int fd,int type)
{
struct flock old_lock, lock;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = type;
lock.l_pid= -1;
fcntl(fd,F_GETLK, &lock);//判断是否可以给文件上锁
if(lock.l_type!= F_UNLCK)
{
/*判断文件不能上锁的原因*/
if (lock.l_type == F_RDLCK)
printf("read lock already set by %d\n",lock.l_pid);
else if(lock.l_type == F_WRLCK)
printf("write lock already set by %d\n", lock.l_pid);
}
lock.l_type=type;//l_type可能已经被F_SETLK修改过。
/*根据不同的type值进行阻塞式上锁或解锁*/
if((fcntl(fd,F_SETLKW, &lock))<0)
{
printf("Lock failed;type = %d\n" ,lock.l_type);
return 1;
}
switch(lock.l_type)
{
case F_RDLCK:
printf("read lock set by %d\n" ,getpid()) ;
break;
case F_WRLCK:
printf("write lock set by %d\n" ,getpid()) ;
break;
case F_UNLCK:
printf("Release lock set by %d\n", getpid());
break;
default:
break;
}
return 0;
}
int main(void)
{
int fd;
fd=open("hello",O_RDWR|O_CREAT,0644);
if(fd<0)
{
printf("Open file error\n");
exit(1);
}
lock_set(fd,F_WRLCK);//给文件上写入锁
getchar();
lock_set(fd,F_UNLCK);//给文件解锁
getchar();
close(fd);
exit(0);
}