fcntl_write.c
/*测试写入锁*/
#include <unistd.h>#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
void lock_set(int fd,int type);
int main(void)
{
int fd;
if((fd=open("/WIN_UBUNTU/sample/fcntl_write/opentest.c",O_CREAT|O_RDWR,0600))<0)
{
perror("open:");
exit(1);
}
else
{
printf("open file: opentest.c %d\n", fd);
}
lock_set(fd,F_WRLCK); /*给文件上写入锁*/
getchar();
lock_set(fd,F_UNLCK); /*解锁*/
getchar();
if(close(fd)<0)
{
perror("close:");
exit(1);
}
else
{
printf("close file: opentest.c %d\n", fd);
}
exit(0);
}
void lock_set(int fd,int type)
{
struct flock lock;
lock.l_whence=SEEK_SET;
lock.l_start =0;
lock.l_len =0;
while(1)
{
lock.l_type=type;
if(fcntl(fd,F_SETLK,&lock)==0) /*给文件上锁或解锁*/
{
if(lock.l_type==F_RDLCK)
{
printf("read lock set by %d\n",getpid());
}
else if(lock.l_type==F_WRLCK)
{
printf("write lock set by %d\n",getpid());
}
else if(lock.l_type==F_UNLCK)
{
printf("release lock set by %d\n",getpid());
}
return;
}
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);
}
getchar();
}
}
}
Makefile
obj=fcntl_write.ofcntl_write:$(obj)
gcc $(obj) -o fcntl_write
fcntl_write.o:fcntl_write.c
gcc -c fcntl_write.c
clean:
rm $(obj) fcntl_write