代码改变世界

文件I/O口编程 -- fcntl使用实例

2013-09-24 21:03  TLLED  阅读(261)  评论(0)    收藏  举报
//lock_set.c

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>


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();
        }
    }
}
 1 //fcntl_write.c
 2 //测试写入锁主函数部分
 3 #include <sys/types.h>
 4 #include <sys/file.h>
 5 #include <sys/stat.h>
 6 #include <unistd.h>
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 #include <fcntl.h>
10 
11 int main(void)
12 {
13     int fd;
14     fd = open("hello.c", O_CREAT | O_RDWR, 0666);
15     if(fd<0) {
16         perror("open:");
17         exit(1);
18     } else {
19         printf("Open file: hello.c %d\n", fd);
20     }
21     
22     //给文件上写入锁
23     lock_set(fd, F_WRLCK);
24     getchar();
25     //给文件解锁
26     lock_set(fd, F_UNLCK);
27     getchar();
28     
29     
30     if(close(fd)<0) {
31         perror("close:");
32         exit(1);
33     } else {
34         printf("Close hello.c \n");
35     }
36     exit(0);
37 }

最后在linux系统下编译:
  gcc -o fcntl_write fcntl_write.c lock_set.c

编译后,执行:

  ./fcntl_write