全部博文(2759)
分类: C/C++
2013-01-23 13:13:52
原文地址:Linux C 学习之 - fcntl 函数 作者:socay2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | include <unistd.h> #include <fcntl.h> #include <stdio.h> 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; }</stdio.h></fcntl.h></unistd.h> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <unistd.h> #include <fcntl.h> #include <stdio.h> 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; }</stdio.h></fcntl.h></unistd.h> |
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 == 当前占用锁的进程。