【linux編程-55】文件加鎖

 

文件加鎖

1. 例子

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

void lock_set(int fd, int type) {
	struct flock lock;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	while (1) {
		lock.l_type = type;
		if ((fcntl(fd, F_SETLK, &lock)) == 0) {
			if (lock.l_type == F_RDLCK)
				printf("read lock set by %d\n", getpid());
			else if(lock.l_type == F_WRLCK)
				printf("write lock set by %d\n", getpid());
			else if (lock.l_type == F_UNLCK)
				printf("release lock by %d\n", getpid());
			return;
		}
		//檢查文件是否可以上鎖
		fcntl(fd, F_GETLK, &lock);
		//判斷不能上鎖的原因
		if (lock.l_type != F_UNLCK) {
			if (lock.l_type == F_RDLCK)
				printf("read lock has been already set by %d\n", getpid());
			else if (lock.l_type == F_WRLCK)
			printf("write lock has been already set by %d\n", getpid());
			getchar();
		}
	}
}
int main() {
	int fd;
	fd = open("data", O_RDWR | O_CREAT, 0666);
	if (fd < 0) {
		perror("open failed");
		return -1;
	}
	lock_set(fd, F_WRLCK);
	getchar();
	lock_set(fd, F_UNLCK);
	getchar();
	close(fd);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章