pipe()函數在子進程產生以前就應該存在。ide
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:onepipe.c 4 > author:donald 5 > details: 6 ==============================================*/ 7 #include <unistd.h> 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #define N 512 12 int main(int argc, const char *argv[]) 13 { 14 int pipefd[2]; 15 pid_t pid; 16 17 if(pipe(pipefd) == -1){ 18 perror("pipe failed"); 19 exit(-1); 20 } 21 printf("%u\n",pid); 22 pid == fork();//這裏一個個大大的bug,本身的誤操做,debug了好久才搞定了 23 printf("%u\n",pid); 24 if(0 == pid){ 25 close(pipefd[1]);//0 read 1 write 26 //一個約定,父子進程都需遵照 27 28 char buf[N]; 29 memset(buf,0,N); 30 read(pipefd[0],buf,N); 31 printf("child read:%s\n",buf); 32 33 printf("child exit\n"); 34 exit(1); 35 }else{ 36 close(pipefd[0]);//0 read 37 char line[N]; 38 printf("parent begin\n"); 39 40 memset(line,0,N); 41 fgets(line,N,stdin); 42 43 write(pipefd[1],line,strlen(line)); 44 printf("parent exit\n"); 45 wait(NULL);//等待子進程的結束 46 } 47 return 0; 48 } 49
父子進程經過管道,進行屢次讀寫操做,先貼上一個比較奇葩的方法(就是一個錯誤):函數
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:my_pipe.c 4 > author:donald 5 > details: 6 ==============================================*/ 7 #include <unistd.h> 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #define N 1024 12 int main(int argc, const char *argv[]) 13 { 14 int fds[2]; 15 if(pipe(fds) == -1){//只能有一對進行讀寫 16 perror("failed"); 17 exit(1); 18 } 19 pid_t pid = fork(); 20 if(pid == -1){ 21 perror("error"); 22 exit(1); 23 } 24 25 while(1){ 26 if(pid == 0){//child read 27 close(fds[1]);//1 write 28 char buf[1024] = ""; 29 read(fds[0],buf,1024);//只能有一個讀, 30 printf("child read:%s\n",buf); 31 //exit(1); 32 }else{//parent write 33 34 close(fds[0]);//0 read 35 // char *p = "hello,donald"; 36 char line[N]; 37 // memset(line,0,N); 38 fgets(line,N,stdin); 39 write(fds[1],line,strlen(line)); 40 //wait(NULL); 41 } 42 } 43 return 0; 44 }
再貼上正確的方法:spa
1 /*============================================ 2 > Copyright (C) 2014 All rights reserved. 3 > FileName:twopipe.c 4 > author:donald 5 > details: 6 ==============================================*/ 7 #include <unistd.h> 8 #include <stdio.h> 9 #include <stdlib.h> 10 #include <string.h> 11 #define N 512 12 int main(int argc, const char *argv[]) 13 { 14 int pipefd[2]; 15 pid_t pid; 16 //pid = fork(); 17 18 if(pipe(pipefd) == -1){ 19 perror("pipe failed"); 20 exit(-1); 21 } 22 pid = fork(); 23 if(pid == 0){ 24 close(pipefd[1]);//0 read 25 char buf[N]; 26 while(1){ 27 memset(buf,0,N); 28 if(read(pipefd[0],buf,N) == 0){ 29 break; 30 } 31 printf("child read:%s\n",buf); 32 } 33 printf("child exit\n"); 34 exit(1); 35 }else{ 36 close(pipefd[0]); 37 char line[N]; 38 while(memset(line,0,N),fgets(line,N,stdin) != NULL ){ 39 write(pipefd[1],line,strlen(line)); 40 } 41 close(pipefd[1]); 42 printf("parent exit\n"); 43 wait(NULL); 44 } 45 return 0; 46 }