分类: LINUX
2014-12-30 11:11:54
#include #include #include
Struct flock{short l_type;off_t l_start;short l_whence;off_t l_len;pid_t l_pid;}
F_RDLCK:读取锁(共享锁)l_type F_WRLCK:写入锁(排斥锁)F_UNLCK:解锁l_stat 相对位移量(字节)SEEK_SET:当前位置为文件的开头,新位置为偏移量的大小SEEK_CUR:当前位置为文件指针的位置,新位置为当前位置加上偏移量l_whence:相对位移量的起点(同lseek 的whence)。SEEK_END:当前位置为文件的结尾,新位置为文件的大小加上偏移量的大小l_len 加锁区域的长度
/*lock_set函数*/void lock_set(int fd, int type){struct flock lock;lock.l_whence = SEEK_SET;//赋值lock结构体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("write lock already set by %d\n",lock.l_pid);getchar();}}}
/*fcntl_write.c测试文件写入锁主函数部分*/#include #include #include #include #include #include int main(void){int fd;/*首先打开文件*/fd=open("hello",O_RDWR | O_CREAT, 0666);if(fd < 0){perror("open");exit(1);}/*给文件上写入锁*/lock_set(fd, F_WRLCK);getchar();/*给文件接锁*/lock_set(fd, F_UNLCK);getchar();close(fd);exit(0);}
[root@localhost file]# ./fcntl_writewrite lock set by 4994release lock by 4994
[root@localhost file]# ./fcntl_writewrite lock already set by 4994write lock set by 4997release lock by 4997
/*fcntl_read.c测试文件读取锁主函数部分*/#include #include #include #include #include #include int main(void){int fd;fd=open("hello",O_RDWR | O_CREAT, 0666);if(fd < 0){perror("open");exit(1);}/*给文件上读取锁*/lock_set(fd, F_RDLCK);getchar();/*给文件接锁*/lock_set(fd, F_UNLCK);getchar();close(fd);exit(0);}
[root@localhost file]# ./fcntl2read lock set by 5009release lock by 5009
[root@localhost file]# ./fcntl2read lock set by 5010release lock by 5010