Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
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 - Fatal编程技术网

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