10.文件鎖

  1. pa文件,對(duì)文件加讀鎖
#include <stdio.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(int argc, char *argv[]){
    printf("getpid: %d\n", getpid());
    struct flock lock;
    lock.l_type = F_RDLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 6;

    //打開(kāi)文件
    int fd = open(argv[1], O_RDONLY);
    if(fd == -1) E_MSG("open", -1);
    //對(duì)指定的文件加讀鎖
    int f = fcntl(fd, F_SETLKW, &lock);
    if(f == -1) E_MSG("fcntl", -1);
    //運(yùn)行到這里,文件加讀鎖成功
    printf("read lock success...\n");
    getchar();
    close(fd);
    return 0;
}
  1. pb文件,對(duì)文件加寫(xiě)鎖
#include <stdio.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(int argc, char *argv[]){
    printf("getpid: %d\n", getpid());
    struct flock lock;
    lock.l_type = F_RDLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 6;

    //打開(kāi)文件, 以寫(xiě)的方式打開(kāi)
    int fd = open(argv[1], O_RDWR);
    if(fd == -1) E_MSG("open", -1);
    //對(duì)指定的文件加寫(xiě)鎖
    int f = fcntl(fd, F_SETLK, &lock);
    if(f == -1) E_MSG("fcntl", -1);
    //運(yùn)行到這里,文件加讀鎖成功
    printf("read lock success...\n");
    getchar();
    close(fd);
    return 0;
}
  1. pc文件
#include <stdio.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define E_MSG(str, value) do{perror(str); return (value);} while(0)
int main(int argc, char *argv[]){
    struct flock lock;
    //open file with read & write
    int fd = open(argv[1], O_RDWR);
    if(fd == -1) E_MSG("OPEN", -1);
    //inital struct members
    lock.l_type = F_RDLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 6;

    //test now, if add lock true
    int cnt = fcntl(fd, F_GETLK, &lock);
    if(cnt == -1) E_MSG("fcntl", -1);
    if(lock.l_type == F_UNLCK) // add lock OK
        printf("Add lock success..\n");
    else //can't add lock
        printf("Pid == %d\n", lock.l_pid);
    close(fd);
    return 0;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容