我想实现以下情况:
- 父进程(即cmd.exe有自己的控制台)
- 子进程 myapp.exe 应该创建新的控制台窗口
- 在子进程中,写入标准输出应该写入父进程控制台
- 如果子进程的 stdout 被重定向到一个文件,保持原样
我已经设法以这种方式创建了单独的控制台:
#include <windows.h>
#include <wincon.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main(int argc, char* argv[])
{
printf("output displayed in parent process\n");
FreeConsole();
AllocConsole();
printf("output displayed in child process console\n");
// how do I redirect stdout to
// that one I've had before FreeConsole?
return 0;
}
(当 stdout 被重定向到文件:myapp.exe > out.txt 时它工作正常)
我已经尝试了很多东西,但没有一个奏效。
int main(int argc, char* argv[])
{
printf("output displayed in parent process\n");
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
FreeConsole();
AllocConsole();
printf("output displayed in child process console\n");
SetStdHandle(STD_OUTPUT_HANDLE,hStdOut);
printf("no success 1\n");
return 0;
}
int main(int argc, char* argv[])
{
printf("output displayed in parent process\n");
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
int fd = _open_osfhandle((intptr_t)hStdOut, _O_TEXT);
FreeConsole();
AllocConsole();
printf("output displayed in child process console\n");
FILE* hf = _fdopen( fd, "w" );
*stdout = *hf;
setvbuf( stdout, NULL, _IONBF, 0 );
printf("no success 2\n");
return 0;
}
最佳答案
进程只能直接写入它所连接的控制台。如果子进程是用自己的控制台创建的,或者一旦启动就分配了自己的控制台,则它不能随后写入父控制台。
如果父进程创建匿名管道,它可以使用写句柄作为子进程的标准输出。父进程需要为管道提供服务;例如它可能有一个线程从管道读取数据并将其写入自己的控制台。
子进程不必担心是写入文件还是写入父进程。这对标准输出来说都是正常的 I/O。
关于c++ - 将标准输出重定向到父进程控制台窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449770/