📄 p10-3.c
字号:
#include <unistd.h>#include <stdio.h>#include <fcntl.h>#include <stdlib.h>#include "filelock.h"#include "err_exit.h"const char *test_file = "/tmp/test_lock";int main() { int file_desc; struct flock region_to_lock; int res; /* 打开文件描述字*/ file_desc = open(test_file, O_RDWR | O_CREAT, 0666); if (!file_desc) err_exit("Unable to open file: test_file"); /* 对区域[10-14]设置读锁 */ printf("Process %d, trying F_RDLCK, region %d to %d\n", getpid(), 10, 14); if (READ_LOCK(file_desc,10,SEEK_SET,5) == -1) { printf("Process %d - failed to lock region\n", getpid()); } else printf("Process %d - obtained lock region\n", getpid()); /* 对区域[10-14]解锁 */ printf("Process %d, trying F_UNLCK, region %d to %d\n", getpid(), 10,14); if (UN_LOCK(file_desc,10,SEEK_SET,5) == -1) { printf("Process %d - failed to unlock region\n", getpid()); } else printf("Process %d - unlocked region\n", getpid()); /* 对区域[0-49]解锁 */ printf("Process %d, trying F_UNLCK, region %d to %d\n", getpid(), 0, 49); if (UN_LOCK(file_desc,0,SEEK_SET,50) == -1) { printf("Process %d - failed to unlock region\n", getpid()); } else printf("Process %d - unlocked region\n", getpid()); /* 对区域[15-20]加写锁 */ printf("Process %d, trying F_WRLCK, region %d to %d\n", getpid(), 15, 15+5); if (WRITE_LOCK(file_desc,15,SEEK_SET,6) == -1) { printf("Process %d - failed to lock region\n", getpid()); } else { printf("Process %d - obtained lock on region\n", getpid()); } /* 对区域[40-49]加读锁 */ printf("Process %d, trying F_RDLCK, region %d to %d\n", getpid(), 40, 49); if (READ_LOCK(file_desc,40,SEEK_SET,10) == -1) { printf("Process %d - failed to lock region\n", getpid()); } else { printf("Process %d - obtained lock on region\n", getpid()); } /* 对区域[16-20]加写锁并等待 */ printf("Process %d, trying F_WRLCK with wait, region %d to %d\n", getpid(), 16, 20); if (WRITEW_LOCK(file_desc,16,SEEK_SET,5) == -1) { printf("Process %d - failed to lock region\n", getpid()); } else { printf("Process %d - obtained lock on region\n", getpid()); } printf("Process %d ending\n", getpid()); close(file_desc);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -