无名管道
1 #include2 #include 3 #include 4 #include 5 6 int main(void) 7 { 8 char buf[1024]; 9 int pipefd[2];10 11 if( pipe( pipefd ) ){ // 创建无名管道12 perror("pipe failed");13 exit(1);14 }15 16 pid_t pid = fork(); // fork 亲缘进程通讯17 if(pid<0){18 perror("fork failed");19 exit;20 }21 22 23 else if(pid>0){ // 父进程发送数据24 close(pipefd[0]); // 关闭读 25 26 while(1){27 bzero(buf,1024);28 fgets(buf,1024,stdin);29 30 write(pipefd[1],buf,strlen(buf));31 32 if(strncmp(buf,"quit",4)==0)33 break;34 }35 exit(0);36 }37 38 else if(pid==0){ // 子进程接收数据39 close(pipefd[1]); // 关闭写40 41 while(1){42 bzero(buf,1024);43 read(pipefd[0],buf,1024);44 printf("chiid read: %s",buf);45 46 if(strncmp(buf,"quit",4)==0)47 break;48 }49 exit(0);50 }51 52 return 0 ;53 }
success !