zoukankan      html  css  js  c++  java
  • 代码示例_IPC_无名管道

    无名管道


     1 #include <unistd.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 #include <string.h>
     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 !


    Stay hungry, stay foolish 待续。。。
  • 相关阅读:
    frog-jump
    nth-digit
    binary-watch
    elimination-game
    evaluate-division
    random-pick-index
    integer-replacement
    rotate-function
    longest-substring-with-at-least-k-repeating-characters
    decode-string
  • 原文地址:https://www.cnblogs.com/panda-w/p/11049435.html
Copyright © 2011-2022 走看看