10.文件锁

2020-08-21  本文已影响0人  陈忠俊
  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;
}
上一篇 下一篇

猜你喜欢

热点阅读