gpt4 book ai didi

c++ - 用 dup 管道传输后如何取回标准输出?

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:06 24 4
gpt4 key购买 nike

int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1],1);
cout<<"hello";//not printed on terminal
fflush(stdout);

现在如何在终端上再次打印或将 mypipe[0] 重定向到标准输出?

最佳答案

最好保存一份标准输出,稍后再恢复。如果 dup2 关闭了 stdout 的最后一个拷贝,您可能无法取回它(例如,没有控制终端、chroot 并且无法访问/dev 或/proc,stdout 是一个匿名管道开始等等)。

int mypipe[2];
pipe(mypipe);

int savstdout=dup(1); // save original stdout
dup2(mypipe[1], 1);
printf("hello"); // not printed on terminal
fflush(stdout);

dup2(savstdout, 1); // restore original stdout

关于c++ - 用 dup 管道传输后如何取回标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16992407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com