[Linux]fcntl函数文件锁概述
生活随笔
收集整理的這篇文章主要介紹了
[Linux]fcntl函数文件锁概述
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述
fcntl函數文件鎖有幾個比較容易忽視的地方:
1.文件鎖是真的進程之間而言的,調用進程絕對不會被自己創建的鎖鎖住,因為F_SETLK和F_SETLKW命令總是替換調用進程現有的鎖(若已存在),所以調用進程決不會阻塞在自己持有的鎖上,于是,F_GETLK命令決不會報告調用進程自己持有的鎖。
2.struct flock結構指針中的l_type成員3個short值分別是:
| 常量 | 值 |
| F_RDLCK | 0 |
| F_WRLCK | 1 |
| F_UNLCK | 2 |
3.如果兩個鎖之間的文件區域有交集,就會阻塞,無論交集的大小。
如圖中section 1持有1到10字節區間的讀鎖,倘若此時需要創建section 2寫鎖,那么需要等待section 1區域釋放才行。
示例代碼:
進程A
#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
extern int *__errno_location(void);
#define errno (*__errno_location())
void report_err(int re);
struct flock section_1 = {
F_RDLCK,
SEEK_SET,
0,
10
};
struct flock section_1_1 = {
F_RDLCK,
SEEK_SET,
0,
10
};
int main(void)
{
int re;
int file = open("/documents/test/test_2", O_RDWR);
printf("open file fd: %d
", file);
//struct flock section_1_1 = section_1;
re = fcntl(file, F_GETLK, §ion_1);
printf("section_1 l_type: %d
", (§ion_1)->l_type);
re = fcntl(file, F_SETLK, §ion_1_1);
report_err(re);
printf("section_1_1 l_type: %d
", (§ion_1_1)->l_type);
sleep(10);
return 0;
}
void report_err(int re)
{
if(re == -1){
perror("file error");
}
}
進程B
#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
extern int *__errno_location(void);
#define errno (*__errno_location())
void report_err(int re);
struct flock section_2 = {
F_WRLCK,
SEEK_SET,
5,
10
};
struct flock section_2_1 = {
F_WRLCK,
SEEK_SET,
5,
10
};
int main(void)
{
int re;
int file = open("/documents/test/test_2", O_RDWR);
printf("open file fd: %d
", file);
re = fcntl(file, F_GETLK, §ion_2);
report_err(re);
printf("section_2 l_type: %d
", (§ion_2)->l_type);
re = fcntl(file, F_SETLKW, §ion_2_1);
report_err(re);
printf("section_2_1 l_type: %d
", (§ion_2_1)->l_type);
return 0;
}
void report_err(int re)
{
if(re == -1){
perror("file error");
}
}
進程A在創建section 1后阻塞10秒,期間啟動進程B創建section 2,此時進程B阻塞等待進程A釋放section 1。
4.鎖與進程和文件關聯。這里有兩重含義:第一重很明顯,當一個進程終止時,它所有建立的鎖全部釋放;第二重則不太明顯,無論一個描述符何時關閉,該進程通過這一描述符引用的文件上的任何一把鎖都會釋放(這些鎖都是該進程設置的),詳情參見《Unix高級環境編程》396頁。
總結
以上是生活随笔為你收集整理的[Linux]fcntl函数文件锁概述的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch forward_pyto
- 下一篇: Vcenter虚拟化三部曲----Vce