[C] Linux中创建管道并使用管道来向自己发送数据 →→→→→进入此内容的聊天室

来自 , 2019-05-14, 写在 C, 查看 121 次.
URL http://www.code666.cn/view/a6ea8471
  1. /*  pipedemo.c  *
  2.  * 创建管道并使用管道来向自己发送数据
  3.  */
  4. #include        <stdio.h>
  5. #include        <unistd.h>
  6.  
  7. main()
  8. {
  9.         int     len, i, apipe[2];       /* two file descriptors */
  10.         char    buf[BUFSIZ];            /* for reading end      */
  11.  
  12.         /* get a pipe */
  13.         if ( pipe ( apipe ) == -1 ){
  14.                 perror("could not make pipe");
  15.                 exit(1);
  16.         }
  17.         printf("Got a pipe! It is file descriptors: { %d %d }\n",
  18.                                                         apipe[0], apipe[1]);
  19.  
  20.         /* read from stdin, write into pipe, read from pipe, print */
  21.  
  22.         while ( fgets(buf, BUFSIZ, stdin) ){
  23.                 len = strlen( buf );
  24.                 if (  write( apipe[1], buf, len) != len ){      /* send */
  25.                         perror("writing to pipe");              /* down */
  26.                         break;                                  /* pipe */
  27.                 }
  28.                 for ( i = 0 ; i<len ; i++ )                     /* wipe */
  29.                         buf[i] = 'X' ;
  30.                 len = read( apipe[0], buf, BUFSIZ ) ;           /* read */
  31.                 if ( len == -1 ){                               /* from */
  32.                         perror("reading from pipe");            /* pipe */
  33.                         break;
  34.                 }
  35.                 if ( write( 1 , buf, len ) != len ){            /* send  */
  36.                         perror("writing to stdout");            /* to    */
  37.                         break;                                  /* stdout */
  38.                 }
  39.         }
  40. }

回复 "Linux中创建管道并使用管道来向自己发送数据"

这儿你可以回复上面这条便签

captcha