檔案鎖
前言
/proc是一個特殊的檔案系統。
該目錄下檔案用來表示與啟動、核心相關的特殊資訊。
可修改該檔案
- /proc/cpuinfo——CPU詳細資訊
- /proc/meminfo——記憶體相關資訊
- /proc/version——版本資訊
- /proc/sys/fs/file-max——系統中能同時打開的檔案總數
- 程序的相關資訊——/proc/32689/ 表示指定程序(程序号為32689)的相關資訊
- /proc/devices——已配置設定的字元裝置、塊裝置的裝置号
檔案鎖
- 用于并發對檔案I/O進行操作
用法
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
參數
- cmd——取值F_GETLK,F_SETLK和F_SETLKW,分别表示擷取鎖、設定鎖、和同步設定鎖。
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。
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME "flock_demo.txt"
int flock_set(int fd, int type) {
printf("pid=%d come in.\n",getpid());
struct flock fflock;
memset(&fflock, 0, sizeof(fflock));
fcntl(fd,F_GETLK,&fflock);
if (fflock.l_type != F_UNLCK) {
if (fflock.l_type == F_RDLCK) {//有鎖,判斷是讀鎖還是寫鎖
printf("flock has been set to read lock by %d\n",fflock.l_pid);
} else if (fflock.l_type == F_WRLCK) {
printf("flock has been set to write lock by %d\n", fflock.l_pid);
}
}
//鎖定檔案
fflock.l_type = type;
fflock.l_whence = SEEK_SET;
fflock.l_start = 0;
fflock.l_len = 0;
fflock.l_pid = -1;
//阻塞式的
if (fcntl(fd,F_SETLKW,&fflock) < 0) {
printf("set lock failed!\n");
return -1;
}
switch (fflock.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("Process pid = %d out.\n",getpid());
return 0;
}
int main(void) {
int fd = 0;
fd = open(FILE_NAME, O_RDWR | O_CREAT, 0666);
if (fd < 0) {
printf("open file %s failed!\n",FILE_NAME);
exit(-1);
}
//flock_set(fd, F_RDLCK); //讀鎖
flock_set(fd, F_WRLCK); //寫鎖
getchar();
flock_set(fd, F_UNLCK); //解鎖
getchar();
close(fd);
return 0;
}
- 寫鎖是排他性的,檔案上了寫鎖,就會阻止其他程式的寫鎖與讀鎖。
- 讀鎖可以多個程式對同一檔案上讀鎖,除此之外其他情況也會失敗(阻止其他程式的讀鎖與寫鎖)。