文件锁
文章目錄
- 1 文件鎖
- 1.1 文件鎖概述
- 1.2 示例代碼
1 文件鎖
1.1 文件鎖概述
并發(fā)對(duì)文件I/O操作的影響,解決辦法?
- 文件鎖
用法: man 2 fcntl。
頭文件:
#include <unistd.h> #include <fcntl.h>函數(shù)定義: int fcntl(int fd, int cmd, ... /* arg */ );
- 參數(shù): cmd 取值 F_GETLK, F_SETLK 和 F_SETLKW ,分別表示獲取鎖、設(shè)置鎖和同步設(shè)置鎖。
文件鎖的表示:
// struct flock 結(jié)構(gòu)體說(shuō)明struct flock {short l_type; /*F_RDLCK, F_WRLCK, or F_UNLCK */off_t l_start; /*offset in bytes, relative to l_whence */short l_whence; /*SEEK_SET, SEEK_CUR, or SEEK_END */off_t l_len; /*length, in bytes; 0 means lock to EOF */pid_t l_pid; /*returned with F_GETLK */ };//l_type: 第一個(gè)成員是加鎖的類(lèi)型:只讀鎖,讀寫(xiě)鎖,或是解鎖。 //l_start和l_whence: 用來(lái)指明加鎖部分的開(kāi)始位置。 //l_len: 是加鎖的長(zhǎng)度。 //l_pid: 是加鎖進(jìn)程的進(jìn)程id。舉例:
- 我們現(xiàn)在需要把一個(gè)文件的前三個(gè)字節(jié)加讀鎖,則該結(jié)構(gòu)體的l_type=F_RDLCK, l_start=0, l_whence=SEEK_SET, l_len=3, l_pid不需要指定,然后調(diào)用fcntl函數(shù)時(shí),cmd參數(shù)使F_SETLK。
1.2 示例代碼
#include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h>#define FILE_NAME "test.txt"int flock_set(int fd, int type) {printf("pid=%d into...\n", getpid());struct flock flock;memset(&flock, 0, sizeof(flock));fcntl(fd, F_GETLK, &flock);if (flock.l_type != F_UNLCK) {if (flock.l_type == F_RDLCK) {printf("flock has been set to read lock by %d\n", flock.l_pid);} else if (flock.l_type == F_WRLCK) {printf("flock has been set to write lock by %d\n", flock.l_pid);}}flock.l_type = type;flock.l_whence = SEEK_SET;flock.l_start = 0;flock.l_len = 0; flock.l_pid = -1;if (fcntl(fd, F_SETLKW, &flock) < 0) {printf("set lock failed!\n");return -1;} switch (flock.l_type) {case F_RDLCK:printf("read lock is set by %d\n", getpid());break;case F_WRLCK:printf("write lock is set by %d\n", getpid());break;case F_UNLCK:printf("lock is released by %d\n", getpid());break;default:break;}printf("pid=%d out.\n", getpid());return 0; }int main(void) {int fd;fd = open(FILE_NAME, O_RDWR|O_CREAT, 0666);if (fd < 0) {printf("open file %s failed!\n", FILE_NAME);}//flock_set(fd, F_WRLCK);flock_set(fd, F_RDLCK);getchar();flock_set(fd, F_UNLCK);getchar();close(fd);return 0; }注意:
總結(jié)
- 上一篇: 烫伤用酱油、牙膏有用吗?
- 下一篇: 通信运营商是做什么的 电信运营商业务