- 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;
}
- 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;
}
- 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;
}