| 1 | = 別人寫的pipe程式 = |
| 2 | |
| 3 | * pipe函式用一個int[]作參數,int[] fd中fd[0]用於讀,fd[1]用於寫 |
| 4 | |
| 5 | {{{ |
| 6 | #!c |
| 7 | #include <stdio.h> |
| 8 | #include <unistd.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <string.h> |
| 11 | #include <sys/types.h> |
| 12 | |
| 13 | int main() |
| 14 | { |
| 15 | int pipe1_fd[2], pipe2_fd[2]; |
| 16 | |
| 17 | char * parent_talks[] = {"Hi, my baby","Can you tell daddy date and time?","Daddy have to leave here, bye!",NULL}; |
| 18 | char * child_talks[] = {"Hi, daddy","Sure,","Bye!",NULL}; |
| 19 | |
| 20 | char parent_buf[256], child_buf[256]; |
| 21 | char * parent_ptr, * child_ptr; |
| 22 | |
| 23 | int i,j, len; |
| 24 | int child_status; |
| 25 | time_t curtime; |
| 26 | |
| 27 | if(pipe(pipe1_fd) < 0) |
| 28 | { |
| 29 | printf("pipe1 create error\n"); |
| 30 | return -1; |
| 31 | } |
| 32 | |
| 33 | if(pipe(pipe2_fd) < 0) |
| 34 | { |
| 35 | printf("pipe2 create error\n"); |
| 36 | return -1; |
| 37 | } |
| 38 | |
| 39 | if(fork() == 0) //child |
| 40 | { |
| 41 | //pipe1_fd[0] is used to read, pipe2_fd[1] is used to write |
| 42 | close(pipe1_fd[1]); |
| 43 | close(pipe2_fd[0]); |
| 44 | |
| 45 | i = 0; |
| 46 | child_ptr = child_talks[i]; |
| 47 | while(child_ptr != NULL) |
| 48 | { |
| 49 | len = read(pipe1_fd[0],child_buf,255); |
| 50 | child_buf[len] = '\0'; |
| 51 | printf("Parent: %s\n",child_buf); |
| 52 | |
| 53 | if(i == 1) |
| 54 | { |
| 55 | time(&curtime); |
| 56 | len = sprintf(child_buf, "%s %s", child_ptr, ctime(&curtime)); |
| 57 | child_buf[len-1] = '\0'; |
| 58 | write(pipe2_fd[1],child_buf,strlen(child_buf)); |
| 59 | } |
| 60 | else |
| 61 | { |
| 62 | write(pipe2_fd[1],child_ptr,strlen(child_ptr)); |
| 63 | } |
| 64 | |
| 65 | child_ptr = child_talks[++i]; |
| 66 | } |
| 67 | |
| 68 | close(pipe1_fd[0]); |
| 69 | close(pipe2_fd[1]); |
| 70 | exit(0); |
| 71 | } |
| 72 | else //parent |
| 73 | { |
| 74 | //pipe1_fd[1] is used to write, pipe2_fd[0] is used to read |
| 75 | close(pipe1_fd[0]); |
| 76 | close(pipe2_fd[1]); |
| 77 | |
| 78 | j = 0; |
| 79 | parent_ptr = parent_talks[j]; |
| 80 | while(parent_ptr != NULL) |
| 81 | { |
| 82 | write(pipe1_fd[1],parent_ptr,strlen(parent_ptr)); |
| 83 | len = read(pipe2_fd[0],parent_buf,255); |
| 84 | parent_buf[len] = '\0'; |
| 85 | printf("Child: %s\n", parent_buf); |
| 86 | parent_ptr = parent_talks[++j]; |
| 87 | } |
| 88 | |
| 89 | close(pipe1_fd[1]); |
| 90 | close(pipe2_fd[0]); |
| 91 | wait(&child_status); |
| 92 | exit(0); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | }}} |
| 97 | |