首页 > 解决方案 > 为什么从 STDOUT_FILENO 重定向到它的管道中读取会挂起而没有显式 endl 或关闭管道的写端?

问题描述

以下代码重定向stdout到管道的写入端,然后我从其读取端读取。

// main.cpp
#include <cassert>
#include <iostream>
#include <unistd.h>

int main( int argc, char* argv[] ) {
  int my_pipe[2] = { -1, -1 };
  char buf[100] = { '\0' };
  int stdout_copy;

  assert( -1 != (stdout_copy = dup( STDOUT_FILENO )) );
  assert( 0 == pipe( my_pipe ) );
  assert( -1 != dup2( my_pipe[1], STDOUT_FILENO ) );
  //close( my_pipe[1] );    // (1) Uncommenting this prevents hang.
  //my_pipe[1] = -1;

  std::cout << "hello"
            //<< std::endl  // (2) Uncommenting this also prevents hang.
            ;

  assert( -1 != dup2( stdout_copy, STDOUT_FILENO ) );

  read( my_pipe[0], buf, sizeof buf );
  std::cout << buf;

  close( my_pipe[0] );

  return 0;
}
$ g++ --version && g++ -g ./main.cpp
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$

玩弄这段代码,我注意到read挂起,除非我(1)我的管道在ing到它close之后的写端,和/或(2)显式地写一个to 。为什么会这样?dup2STDOUT_FILENOstd::endlstd::cout

起初,我认为这个问题与刷新有关stdout- 这可能已经解释了显式 write 的需要std::endl,但是(根据我可能不完整的理解)这并不能解释为什么关闭管道的 write-end 会阻止挂起。


更新:我发现这很有趣:当 (1) 和 (2) 都被评论时,std::cout << "hello\n";不会阻止挂起;即它不是“等同于” std::cout << "hello" << std::endl;.

标签: c++stdoutdup2dup

解决方案


推荐阅读