文件锁
文章目錄
- 1 文件鎖
- 1.1 文件鎖概述
- 1.2 示例代碼
1 文件鎖
1.1 文件鎖概述
并發對文件I/O操作的影響,解決辦法?
- 文件鎖
用法: man 2 fcntl。
頭文件:
#include <unistd.h> #include <fcntl.h>函數定義: int fcntl(int fd, int cmd, ... /* arg */ );
- 參數: cmd 取值 F_GETLK, F_SETLK 和 F_SETLKW ,分別表示獲取鎖、設置鎖和同步設置鎖。
文件鎖的表示:
// struct flock 結構體說明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: 第一個成員是加鎖的類型:只讀鎖,讀寫鎖,或是解鎖。 //l_start和l_whence: 用來指明加鎖部分的開始位置。 //l_len: 是加鎖的長度。 //l_pid: 是加鎖進程的進程id。舉例:
- 我們現在需要把一個文件的前三個字節加讀鎖,則該結構體的l_type=F_RDLCK, l_start=0, l_whence=SEEK_SET, l_len=3, l_pid不需要指定,然后調用fcntl函數時,cmd參數使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; }注意:
總結
- 上一篇: 烫伤用酱油、牙膏有用吗?
- 下一篇: 通信运营商是做什么的 电信运营商业务