C++ 用dup配管后如何取回stdout? int-mypipe[2]; 管道(mypipe); int dupstdout=dup2(mypipe[1],1); 不能包含 #包括 #包括 #包括 #包括 int main(){ int mypipe[2]; 管道(mypipe); int dupstdout=dup2(mypipe[1],1); printf(“hello”);//未在终端上打印 fflush(stdout); 关闭(dupstdout); int fd=打开(“/dev/tty”,仅限O_wr); 标准输出=fdopen(fd,“w”); printf(“再次你好”\n”); }
无论如何,最好不要关闭C++ 用dup配管后如何取回stdout? int-mypipe[2]; 管道(mypipe); int dupstdout=dup2(mypipe[1],1); 不能包含 #包括 #包括 #包括 #包括 int main(){ int mypipe[2]; 管道(mypipe); int dupstdout=dup2(mypipe[1],1); printf(“hello”);//未在终端上打印 fflush(stdout); 关闭(dupstdout); int fd=打开(“/dev/tty”,仅限O_wr); 标准输出=fdopen(fd,“w”); printf(“再次你好”\n”); },c++,linux,pipe,file-descriptor,C++,Linux,Pipe,File Descriptor,无论如何,最好不要关闭stdout 如果作为第二个参数传递给dup2()的描述符已打开,dup2()将忽略所有错误关闭它。显式使用close()和dup()更安全 最好保存一份standard out的副本,以后再恢复。如果dup2关闭了stdout的最后一个副本,您可能无法取回它(例如,没有控制终端,chroot'd,无法访问/dev或/proc,stdout最初是一个匿名管道,等等) 新fd是否指实际的/dev/pts/x?是的,/dev/tty是进程的控制终端,即启动程序的终端,除非您将其
stdout
如果作为第二个参数传递给
dup2()
的描述符已打开,dup2()
将忽略所有错误关闭它。显式使用close()
和dup()
更安全 最好保存一份standard out的副本,以后再恢复。如果dup2
关闭了stdout的最后一个副本,您可能无法取回它(例如,没有控制终端,chroot'd,无法访问/dev或/proc,stdout最初是一个匿名管道,等等)
新fd是否指实际的/dev/pts/x?是的,
/dev/tty
是进程的控制终端,即启动程序的终端,除非您将其分离并重新连接到另一个终端。
int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1],1);
cout<<"hello";//not printed on terminal
fflush(stdout);
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1], 1);
printf("hello");//not printed on terminal
fflush(stdout);
close(dupstdout);
int fd = open("/dev/tty", O_WRONLY);
stdout = fdopen(fd, "w");
printf("hello again\n");
}
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