p10-6.c

来自「SUN Solaris8平台下进程间通信」· C语言 代码 · 共 39 行

C
39
字号
#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 + =
减小字号Ctrl + -
显示快捷键?