int main(void) { int fd; pid_t pid; if ((fd = creat("templock", FILE_MODE)) < 0) err_sys("creat error"); if (write(fd, "ab", 2) != 2) err_sys("write error"); TELL_WAIT(); if ((pid = fork()) < 0){ err_sys("fork error"); }else if(pid == 0){/*child*/ lockabyte("child", fd, 0); TELL_PARENT(getppid()); WAIT_PARENT(); lockabyte("child", fd, 1); }else{ lockabyte("parent", fd, 1); TELL_CHILD(pid); WAIT_CHILD(); lockabyte("parent", fd, 0); } exit(0); }
int main(int argc, char *argv[]) { int fd; pid_t pid; /*Create a file and write two bytes to it*/ fd = Open("templock", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE) ; if(write(fd, "ab", 2) != 2) err_sys("write error"); TELL_WAIT(); pid = Fork(); if(pid == 0) { lockabyte("child", fd, 0); TELL_PARENT(getppid()); WAIT_PARENT(); lockabyte("child", fd, 1); }else { lockabyte("parent", fd, 1); TELL_CHILD(pid); WAIT_CHILD(); lockabyte("parent", fd, 0); } return 0; }
/* gcc apue.h apue_err.c figure-14.5.c figure-10.24.c figure-14.7.c */ int main(void) { int fd; pid_t pid; /* * Create a file and write two bytes to it. */ if ((fd = creat("templock", FILE_MODE)) < 0) err_sys("creat error"); if (write(fd, "ab", 2) != 2) err_sys("write error"); TELL_WAIT(); /* figure-10.24.c */ if ((pid = fork()) < 0) { err_sys("fork error"); } else if (pid == 0) { /* child */ lockabyte("child", fd, 0); TELL_PARENT(getppid()); WAIT_PARENT(); lockabyte("child", fd, 1); } else { /* parent */ lockabyte("parent", fd, 1); TELL_CHILD(pid); WAIT_CHILD(); lockabyte("parent", fd, 0); } exit(0); }
int main(int argc, char* argv[]) { int fd; pid_t pid; if((fd = creat("templock", FILEMODE)) < 0) printf("creat error"); if(write(fd, "ab", 2) != 2) printf("write error"); TELL_WAIT(); if((pid = fork()) < 0) printf("fork error"); else if(pid == 0) { lockabyte("child:", fd, 0); TELL_PARENT(getpid()); WAIT_PARENT(); lockabyte("child:", fd, 1); } else { lockabyte("parent:", fd, 1); TELL_CHILD(pid); WAIT_CHILD(); lockabyte("parent:", fd, 0); } exit(0); }
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) { /* 子執行緒 */ lockabyte("child", fd, 1); sleep(2); /* 留出時間以便父執行緒鎖住位元組2 */ lockabyte("child", fd, 2); } else { /* 父執行緒 */ lockabyte("parent", fd, 2); sleep(2); /* 留出時間以便子執行緒鎖住位元組1 */ lockabyte("parent", fd, 1); } exit(EXIT_SUCCESS); }