分类: C/C++
2014-11-11 11:45:03
原文地址:Linux C 学习之 - fcntl 函数 作者:socay2
include#include #include int main() { int fd; int ret; struct flock rflk, wflk; fd = open("txt", O_RDONLY); if(fd < 0) { perror("open failed"); return 1; } ret = fcntl(fd, F_GETFD); printf("current descriptor flags: %d\n", ret); fcntl(fd, F_SETFD, 1); printf("current descriptor flags: %d\n", ret); rflk.l_type = F_RDLCK; rflk.l_whence = SEEK_SET; rflk.l_start = 0; rflk.l_len = 10; wflk = rflk; wflk.l_type = F_WRLCK; if(fcntl(fd, F_SETLK, &rflk) == -1) { perror("read lock failed"); return 1; } if(fcntl(fd, F_SETLK, &wflk) == -1) { perror("write lock failed"); return 1; } close(fd); return 0; }
#include编译执行结果为:#include #include int main() { int fd; int ret; struct flock rflk, wflk; fd = open("txt", O_RDWR); if(fd < 0) { perror("open failed"); return 1; } ret = fcntl(fd, F_GETFD); printf("current descriptor flags: %d\n", ret); fcntl(fd, F_SETFD, 1); printf("current descriptor flags: %d\n", ret); rflk.l_type = F_RDLCK; rflk.l_whence = SEEK_SET; rflk.l_start = 0; rflk.l_len = 10; wflk = rflk; wflk.l_type = F_WRLCK; if(fcntl(fd, F_SETLK, &rflk) == -1) { perror("read lock failed"); return 1; } if(fcntl(fd, F_SETLK, &wflk) == -1) { perror("write lock failed"); return 1; } if(fork()) { if(fcntl(fd, F_SETLK, &rflk) == -1) { fprintf(stderr, "parent read lock failed\n"); } if(fcntl(fd, F_SETLK, &wflk) == -1) { fprintf(stderr, "parent write lock failed\n"); } sleep(3); } else { sleep(1); if(fcntl(fd, F_SETLK, &rflk) == -1) { fprintf(stderr, "child read lock failed\n"); } if(fcntl(fd, F_SETLK, &wflk) == -1) { fprintf(stderr, "child write lock failed\n"); } } close(fd); return 0; }
1、在同一进程可以加多次读锁,多次写锁,并且可以同时存在!
上次这里说错了,在同一进程中,锁也并不是同时存在的,而是后面加的锁会覆盖前面加的锁!(2013/1/24修改)
2、在不同进程中,如果进程A拥有读锁或写锁, 那么进程B只能有读锁,不能加写锁3、还需要注意的是,在上面加锁的时候我们把 fcntl 的第二个参数cmd 都置为 F_SETLK,如果把它换成 F_SETLKW,那么在不同进程间可同时加读写锁。假设进程A先拥有了某个锁,进程B想给自己加一把锁,那么就会等到进程A把锁释放掉!
4、如果调用 fcntl(fd, F_GETLK, &flk) 时,如果能够得到这样的锁,那么设置 flk.l_type == F_UNLCK, flk 其他成员值不变; 否则,如果不能得到这样的锁,重新设置 flk 的值,使 l_pid == 当前占用锁的进程。