10.文件锁

  1. pa文件,对文件加读锁
#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;

    //打开文件
    int fd = open(argv[1], O_RDONLY);
    if(fd == -1) E_MSG("open", -1);
    //对指定的文件加读锁
    int f = fcntl(fd, F_SETLKW, &lock);
    if(f == -1) E_MSG("fcntl", -1);
    //运行到这里,文件加读锁成功
    printf("read lock success...\n");
    getchar();
    close(fd);
    return 0;
}
  1. pb文件,对文件加写锁
#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;

    //打开文件, 以写的方式打开
    int fd = open(argv[1], O_RDWR);
    if(fd == -1) E_MSG("open", -1);
    //对指定的文件加写锁
    int f = fcntl(fd, F_SETLK, &lock);
    if(f == -1) E_MSG("fcntl", -1);
    //运行到这里,文件加读锁成功
    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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容