日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

[Linux]fcntl函数文件锁概述

發布時間:2023/12/13 综合教程 30 生活家
生活随笔 收集整理的這篇文章主要介紹了 [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, &section_1);
    printf("section_1 l_type: %d
", (&section_1)->l_type);
    re = fcntl(file, F_SETLK, &section_1_1);
    report_err(re);
    printf("section_1_1 l_type: %d
", (&section_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, &section_2);
    report_err(re);
    printf("section_2 l_type: %d
", (&section_2)->l_type);
    re = fcntl(file, F_SETLKW, &section_2_1);
    report_err(re);
    printf("section_2_1 l_type: %d
", (&section_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函数文件锁概述的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。