- 论坛徽章:
- 0
|
/*fcntl 测试文件主函数*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
void lock_set(int fd,int type);
int main(void)
{
int fd;
fd=open("/home/source/local/src/hello.c",O_CREAT|O_RDWR,0666);
if(fd<0)
{
perror("open:");
exit(1);
}
else
printf("open the file temp.c");
/*给文件上写入锁*/
lock_set(fd,F_WRLCK);
getchar();
/*给文件上解锁*/
lock_set(fd,F_UNLCK);
getchar();
close(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;
/*根据不同的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 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("read lock already set by %d\n",lock.l_pid);
}
}
}
[[i] 本帖最后由 tige 于 2008-11-14 11:14 编辑 [/i]] |
|