📄 p10-2.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(void){ int file_desc; int res; int byte_count; char *byte_to_write = "A"; struct flock region_1,region_2; /* 打开文件描述字 */ file_desc = open(test_file,O_RDWR|O_CREAT,0666); if(!file_desc) err_exit("Unable to open file: test_file"); /* 写入数据 */ for(byte_count = 0; byte_count<100; byte_count++) write(file_desc, byte_to_write, 1); printf("Process %d locking file\n", getpid()); /* 在区域1(从字节10至29)设置共享读锁 */ if (READ_LOCK(file_desc, 10, SEEK_SET, 20) == -1) fprintf(stderr,"Failed to lock region 1\n"); /* 在区域2(从字节40至49)设置互斥写锁 */ if (WRITE_LOCK (file_desc, 40, SEEK_SET, 10) == -1) fprintf(stderr,"Failed to lock region 2\n"); /* 等待以便另一个程序测试锁 */ pause(); printf("Process %d closeing file\n",getpid()); close(file_desc);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -