c++ - 为什么从 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 。为什么会这样?dup2
STDOUT_FILENO
std::endl
std::cout
起初,我认为这个问题与刷新有关stdout
- 这可能已经解释了显式 write 的需要std::endl
,但是(根据我可能不完整的理解)这并不能解释为什么关闭管道的 write-end 会阻止挂起。
更新:我发现这很有趣:当 (1) 和 (2) 都被评论时,std::cout << "hello\n";
不会阻止挂起;即它不是“等同于” std::cout << "hello" << std::endl;
.
解决方案
推荐阅读
- python-2.7 - Odoo : Outcomin 邮件服务器
- expo-web - 如何在世博会的网络浏览器中使用 sessionStorage
- c++ - 我从 std::set 得到 const_iterator 而不是迭代器
- ios - 如何在 iOS 中播放音频样本
- python - MQTT 客户端仅在重新启动代理后连接
- dxf - 如何获取 DXF 文件中每个实体的图纸空间?
- javascript - 下一个.js。docker 镜像所需的文件
- java - DROOLS- 6.5 版与 java 8 的兼容性?
- javascript - switch case 直接到 end case
- javascript - 合并对象以获得数组中的平均值