VS++ 管道程序獲取CMD返回值
阿新 • • 發佈:2018-12-19
int ExecDosCmdRet(CString strCmd, CString& strResult) { SECURITY_ATTRIBUTES sa; HANDLE hRead, hWrite; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (!CreatePipe(&hRead, &hWrite, &sa, 0)) { return FALSE; } STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; //把建立程序的標準錯誤輸出重定向到管道輸入 si.hStdOutput = hWrite; //把建立程序的標準輸出重定向到管道輸入 si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; //關鍵步驟,CreateProcess函式引數意義請查閱MSDN if (!CreateProcess(NULL, strCmd.GetBuffer(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { CloseHandle(hWrite); CloseHandle(hRead); return FALSE; } CloseHandle(hWrite); char buffer[4096] = { 0 }; //用4K的空間來儲存輸出的內容,只要不是顯示檔案內容,一般情況下是夠用了。 DWORD bytesRead; while (true) { if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL) break; strResult += buffer; } CloseHandle(hRead); return pi.dwThreadId; }
int CScanWeakPasswd::ExecDosCmdRet(CString strCmd, CString& strResult) { SECURITY_ATTRIBUTES sa; HANDLE hRead, hWrite; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (!CreatePipe(&hRead, &hWrite, &sa, 0)) { return FALSE; } STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(STARTUPINFO)); DWORD dwExitCode = 0; si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; //把建立程序的標準錯誤輸出重定向到管道輸入 si.hStdOutput = hWrite; //把建立程序的標準輸出重定向到管道輸入 si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; //關鍵步驟,CreateProcess函式引數意義請查閱MSDN if (!CreateProcess(NULL, strCmd.GetBuffer(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) { CloseHandle(hWrite); CloseHandle(hRead); return FALSE; } WaitForSingleObject(pi.hProcess,INFINITE); ////這兩行不一樣 GetExitCodeProcess(pi.hProcess,&dwExitCode); ////這兩行不一樣,等待程序自身給予的返回值 CloseHandle(hWrite); char buffer[4096] = { 0 }; //用4K的空間來儲存輸出的內容,只要不是顯示檔案內容,一般情況下是夠用了。 DWORD bytesRead; while (true) { if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL) break; strResult = buffer; } CloseHandle(hRead); return dwExitCode; }