[Linux]fcntl函数文件锁概述
概述
fcntl函數(shù)文件鎖有幾個(gè)比較容易忽視的地方:
1.文件鎖是真的進(jìn)程之間而言的,調(diào)用進(jìn)程絕對(duì)不會(huì)被自己創(chuàng)建的鎖鎖住,因?yàn)镕_SETLK和F_SETLKW命令總是替換調(diào)用進(jìn)程現(xiàn)有的鎖(若已存在),所以調(diào)用進(jìn)程決不會(huì)阻塞在自己持有的鎖上,于是,F(xiàn)_GETLK命令決不會(huì)報(bào)告調(diào)用進(jìn)程自己持有的鎖。
2.struct flock結(jié)構(gòu)指針中的l_type成員3個(gè)short值分別是:
| 常量 | 值 |
| F_RDLCK | 0 |
| F_WRLCK | 1 |
| F_UNLCK | 2 |
3.如果兩個(gè)鎖之間的文件區(qū)域有交集,就會(huì)阻塞,無論交集的大小。
如圖中section 1持有1到10字節(jié)區(qū)間的讀鎖,倘若此時(shí)需要?jiǎng)?chuàng)建section 2寫鎖,那么需要等待section 1區(qū)域釋放才行。
示例代碼:
進(jìn)程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");
}
}
進(jìn)程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");
}
}
進(jìn)程A在創(chuàng)建section 1后阻塞10秒,期間啟動(dòng)進(jìn)程B創(chuàng)建section 2,此時(shí)進(jìn)程B阻塞等待進(jìn)程A釋放section 1。
4.鎖與進(jìn)程和文件關(guān)聯(lián)。這里有兩重含義:第一重很明顯,當(dāng)一個(gè)進(jìn)程終止時(shí),它所有建立的鎖全部釋放;第二重則不太明顯,無論一個(gè)描述符何時(shí)關(guān)閉,該進(jìn)程通過這一描述符引用的文件上的任何一把鎖都會(huì)釋放(這些鎖都是該進(jìn)程設(shè)置的),詳情參見《Unix高級(jí)環(huán)境編程》396頁。
總結(jié)
以上是生活随笔為你收集整理的[Linux]fcntl函数文件锁概述的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch forward_pyto
- 下一篇: python3 for_Python3: