📄 p10-6.c
字号:
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <stdio.h>#include "err_exit.h"#include "filelock.h"void lockabyte(const char *, int , off_t);int main(void){ int fd; pid_t pid; /* 创建文件并写二个字节*/ if ((fd = creat("templock", 0666)) < 0) err_exit("creat error"); write(fd, "ab", 2) ; if((pid = fork()) < 0) err_exit("fork error"); if (pid == 0) { /* 子进程 */ lockabyte("child", fd, 1); sleep(10); /* 留出时间以便父进程先锁住字节2 */ lockabyte("child", fd, 2); } else { /* 父进程 */ lockabyte("parent", fd, 2); sleep(10); /* 留出时间以便子进程先锁住字节1 */ lockabyte("parent", fd, 1); } exit(EXIT_SUCCESS);}static void lockabyte(const char *name, int fd, off_t offset){ if (WRITEW_LOCK(fd, offset, SEEK_SET, 1) <0 ) { fprintf(stderr,"%s: ",name); err_exit("WRITEW_LOCK error"); } printf("%s: got the lock,byte %d\n",name, offset);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -