多进程demo
多进程实现DOS重定向输出,界面如下:
主要的代码实现如下:
1 #define MAXREADBUFFERLEN (60 * 1000) 2 3 void CRedirectDlg::OnBnClickedButtonRun() 4 { 5 // TODO: Add your control notification handler code here 6 UpdateData(TRUE); 7 CString strCommand, strFileName(_T("Redirect.txt")); 8 m_strCommand.TrimRight(_T(" ")); 9 if (m_strCommand == _T("")) 10 { 11 return; 12 } 13 strCommand.Format(_T("cmd.exe /c \"%s\">%s"), m_strCommand, strFileName); 14 15 //创建一个不要出现DOS窗口的、影藏的命令执行线程 16 STARTUPINFO si; 17 ZeroMemory(&si, sizeof(si)); 18 si.cb = sizeof(STARTUPINFO); 19 si.wShowWindow = SW_HIDE; 20 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 21 PROCESS_INFORMATION pi; 22 BOOL res = CreateProcess(NULL, strCommand.GetBuffer(0), NULL, NULL, NULL, 23 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &si, &pi); 24 if (!res) 25 { 26 AfxMessageBox(_T("创建线程出错。")); 27 return; 28 } 29 30 //等待进程执行完毕 31 WaitForSingleObject(pi.hProcess, INFINITE); 32 33 //如果打开文件失败,则有可能文件仍在使用中,可以多次读取 34 TCHAR szBuff[MAXREADBUFFERLEN] = { 0 }; 35 BOOL bSuccess = FALSE; 36 try 37 { 38 CFile file; 39 if (file.Open(strFileName, CFile::modeReadWrite, NULL)) 40 { 41 file.Read((TCHAR*)szBuff, MAXREADBUFFERLEN); 42 file.Close(); 43 bSuccess = TRUE; 44 } 45 } 46 catch (CFileException e) 47 { 48 Sleep(1000); 49 } 50 51 //如果打开文件成功,则删除临时文件,并显示出结果 52 if (bSuccess) 53 { 54 DeleteFile(strFileName); 55 m_strResult.Format(_T("%s"), (TCHAR*)szBuff); 56 } 57 else 58 { 59 AfxMessageBox(_T("程序执行出错。"), MB_ICONERROR | MB_OK); 60 } 61 62 UpdateData(FALSE); 63 }