【问题标题】:How can I write more values to a pipe and read them?如何将更多值写入管道并读取它们?
【发布时间】:2011-10-09 13:34:19
【问题描述】:

我在 linux 下用 c++ 编写了一个程序,其中子进程应该将两个长值写入管道,父进程应该读取它们。到目前为止,我 onlz 设法为此设置了两个(命名的)管道,并通过 write(fd1,&value1,sizeof(long)) 写入每个管道,并通过 read(fd1, &value1, sizeof(long)) 读取它。 两个都用一根管子会更好,但我不知道该怎么做。

我试过了:

write(fd1,&value1,sizeof(long));

write(fd1,&value2,sizeof(long));

还有两次读取,但这似乎会导致进程阻塞并相互等待。

如果有人能给我一个提示,我会很高兴如何实现这一点。

可能的解决方案:我将所有值写入一个数组(因为我知道有多少),然后我只需要一个线/读取调用。

【问题讨论】:

  • 管道可能被缓冲了你刷新它们了吗?

标签: c++ linux process pipe


【解决方案1】:

它应该可以正常工作。这是一个非常简单的例子。它主要是代码from the example in the man page 的副本。

int main(int argc, char *argv[])
{
   int fd[2];
   pid_t cpid;
   int ret;
   int val = 0;
   if (pipe(fd) == -1)
      {
      perror("pipe"); exit(EXIT_FAILURE);
      }
   cpid = fork();
   if (cpid == -1)
      {
      perror("fork"); exit(EXIT_FAILURE);
      }
   if (cpid == 0) { 
      // close write end of pipe in child
      close(fd[1]);   
      ret = read(fd[0], &val, sizeof( val ));
      printf( "1: result = %d, value = %d\n", ret, val );
      ret = read(fd[0], &val, sizeof( val ));
      printf( "2: result = %d, value = %d\n", ret, val );
      close(fd[0]);
      _exit(EXIT_SUCCESS);
      } 
   else {
      // close read end of pipe in parent
      close(fd[0]); 
      val = 42;
      if ( write(fd[1], &val, sizeof(val)) < 0 )
         perror( "write" );
      val++;
      if ( write(fd[1], &val, sizeof(val)) < 0 )
         perror( "write" );
      close(fd[1]); 
      wait(NULL); 
      exit(EXIT_SUCCESS);
      }
}

【讨论】:

    【解决方案2】:

    您应该检查您的 read() 的返回值,这两个 long 将最终(并且可能)一起发送到接收进程。在这种情况下,您需要将接收到的缓冲区拆分为两个 long。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多