【发布时间】:2015-02-11 12:37:15
【问题描述】:
我想实现以下情况:
- 父进程(即cmd.exe有自己的控制台)
- 子进程 myapp.exe 应该创建新的控制台窗口
- 在子进程中,写入标准输出应写入父进程控制台
- 如果子进程的标准输出被重定向到一个文件,保持原样
我已经设法以这种方式创建了单独的控制台:
#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;
}
(在标准输出重定向到文件的情况下可以正常工作: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;
}
【问题讨论】:
-
TL;DR;你要Pipe吗?
-
在创建新的控制台窗口后,我希望能够写入我的应用程序在开始时(在我从默认控制台分离之前)能够写入的流。如果您认为管道可以帮助我以这种方式工作,请对这种解决方案有所了解。
标签: c++ c winapi stdout windows-console