c - 管道上的多次读写

标签 c unix operating-system pipe

我不是很清楚管道是如何工作的。对于下面的程序。父进程两次写入管道,子进程两次从管道读取,但在第二次读取时,似乎子进程只读取一个字符。这 程序的输出是:

[2297]:my bufin is {empty}, my bufout is {hello}

[2298]:my bufin is {a}, my bufout is {hello}

为什么子进程的 bufin 是 a 而不是//aaa。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 10

int main( void ) {
   char bufin[ BUFSIZE ] = "empty";
   char bufout[] = "hello";
   char b[] = "//aaa";
   int bytesin;
   pid_t childpid;
   int fd[ 2 ];
   if ( pipe( fd ) == -1 ) {
      perror( "Failed to create the pipe" );
      return 1;
   }
   bytesin = strlen( bufin );
   childpid = fork();
   if ( childpid == -1 ) {
      perror( "Failed to fork" );
      return 1; 
   }
   if ( childpid ) {      /* parent code */
      // Parent node write to the pipe.       
      write( fd[ 1 ], bufout, strlen( bufout ) + 1 );
      write( fd[ 1 ], b, strlen(b) + 1 ); // Just for trying
   }
   else {                 /* child code */
      bytesin = read( fd[ 0 ], bufin, BUFSIZE );
      bytesin = read( fd[ 0 ], bufin, BUFSIZE );  // Just for trying  
   }    
   fprintf(stderr, "[%ld]:my bufin is {%.*s}, my bufout is {%s}\n",
           (long)getpid(), bytesin, bufin, bufout);
   return 0; 
}

最佳答案

在第一次读取时,您要求 BUFSIZE 个字节,因此读取得到 'hello\0//aa'(恰好 10 个字符)。当您打印它时,您只会看到“hello”,因为后面有 NULL 字符。只剩下要阅读的字符是一个“a”字母,您会在第二次阅读后看到它。您还忘记了关闭父项和子项中未使用的管道末端。请引用非常好的管道指南:http://beej.us/guide/bgipc/output/html/multipage/pipes.html

关于c - 管道上的多次读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569943/

相关文章:

c - EVP_get_digestbyname : what is this . .?

C中创建shell,execv()无法执行大部分命令

linux - SSH 隧道将数据从一个数据中心传输到另一个数据中心的中间机器

python - 我已经安装了 libpng,但是在安装 autopy 时出现错误 "' png.h' file not found #include <png.h>"

c - 为什么 bash 在分配时不自动导出 PATH?

windows - 如何通过扫描码(不是虚拟键码)获取键状态?

c - Scanf输入及其他问题

c - 用数组模拟列表

c++ - int的C赋值

c - 测量 Mutex 和 Busy waiting 的效率