控制台程序输出重定向
摘自:http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=185751
void CDosWindowsDlg::OnButton1()
{
// TODO: Add your control notification handler code here
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0)) {
MessageBox("Error On CreatePipe()");
return;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW ¦ STARTF_USESTDHANDLES;
if (!CreateProcess(NULL,"cmd.exe /c dir /?"
,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) {
MessageBox("Error on CreateProcess()");
return;
}
CloseHandle(hWrite);
char buffer[4096] = {0};
DWORD bytesRead;
while (true) {
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
m_Edit1 += buffer;//m_Edit1是CString
UpdateData(false);
Sleep(200);
}
}
补充:
上面的方法会出现下面的情况:
CreateProcess启动的进程结束后,主进程不会结束,调试发现,进程卡在了ReadFile这个函数中,该函数不返回。搜索了一下,找到如下解决办法:
在ReadFile之前,先调用PeekNamedPipe()来判断管道中是否有数据可以读取,有则调用ReadFile,没有则略过。
void CDosWindowsDlg::OnButton1()
{
// TODO: Add your control notification handler code here
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0)) {
MessageBox("Error On CreatePipe()");
return;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW ¦ STARTF_USESTDHANDLES;
if (!CreateProcess(NULL,"cmd.exe /c dir /?"
,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) {
MessageBox("Error on CreateProcess()");
return;
}
CloseHandle(hWrite);
char buffer[4096] = {0};
DWORD bytesRead;
while (true) {
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
m_Edit1 += buffer;//m_Edit1是CString
UpdateData(false);
Sleep(200);
}
}
补充:
上面的方法会出现下面的情况:
CreateProcess启动的进程结束后,主进程不会结束,调试发现,进程卡在了ReadFile这个函数中,该函数不返回。搜索了一下,找到如下解决办法:
在ReadFile之前,先调用PeekNamedPipe()来判断管道中是否有数据可以读取,有则调用ReadFile,没有则略过。