windows C++捕獲CMD命令輸出
阿新 • • 發佈:2020-08-01
1 #include "windows.h" 2 #include "stdio.h" 3 #include <string> 4 #include <iostream> 5 6 HANDLE hReadPipeCmd = NULL; 7 HANDLE hWritePipeCmd = NULL; 8 HANDLE hReadPipeShell = NULL; 9 HANDLE hWritePipeShell = NULL;//shell 10 HANDLE hProcessHandle; //程序控制代碼 11 12 charreadBuff[4096]="\x00"; 13 char writeBuff[256]="\x00"; 14 //BOOL initPipeSuccess = FALSE; 15 16 void initPipe(); 17 //void shell(); 18 DWORD WINAPI shell(LPVOID lpThreadParameter); 19 20 int main(int argc, char* argv[]) 21 { 22 CreateThread(NULL, 0, shell, NULL, 0, 0); 23 std::string cmd; 24while(1) 25 { 26 //scanf("%s",writeBuff); 27 std::cin.getline(writeBuff, sizeof(writeBuff)); 28 //cmd += "\r\n"; 29 //memcpy(writeBuff, cmd.c_str(), cmd.size()); 30 strcat(writeBuff,"\r\n");//這個是關鍵,必須加上回車換行!否則不會回顯! 31 32 33 //shell(); 34 //printf("%s", readBuff);//很關鍵35 //memset(readBuff, 0, sizeof(readBuff)); 36 37 //getchar(); 38 } 39 } 40 DWORD WINAPI shell(LPVOID lpThreadParameter) 41 //void shell() 42 { 43 //if(initPipeSuccess == FALSE) 44 initPipe(); 45 46 47 48 //Sleep(1000); 49 50 unsigned long BytesRead = 0; 51 DWORD TotalBytesAvail; 52 53 //檢查管道中是否有資料 54 while (PeekNamedPipe(hReadPipeCmd,readBuff, sizeof(readBuff), &BytesRead, &TotalBytesAvail, NULL)) 55 { 56 if (TotalBytesAvail <= 0) 57 { 58 if (strlen(writeBuff) > 0) 59 { 60 DWORD dwByteWritten; 61 62 WriteFile(hWritePipeShell, writeBuff, strlen(writeBuff), &dwByteWritten, 0);//寫管道 63 //printf("寫入位元組數:%d\n", dwByteWritten); 64 memset(writeBuff, 0, 256); 65 } 66 67 Sleep(600); 68 } 69 else 70 { 71 //printf("有資料到來!\n"); 72 memset(readBuff, 0, sizeof(readBuff)); 73 if(BytesRead==TotalBytesAvail) 74 { 75 ReadFile(hReadPipeCmd, readBuff, TotalBytesAvail+100, &BytesRead, NULL); 76 printf("%s", readBuff);//很關鍵 77 memset(readBuff, 0, sizeof(readBuff)); 78 //break; 79 } 80 } 81 } 82 return 0; 83 } 84 //建立雙管道和建立cmd程序 85 void initPipe() 86 { 87 SECURITY_ATTRIBUTES sa = {0}; 88 STARTUPINFO si = {0}; 89 PROCESS_INFORMATION pi = {0}; 90 91 sa.nLength = sizeof(sa); 92 sa.lpSecurityDescriptor = NULL; 93 sa.bInheritHandle = TRUE; 94 //建立管道 95 CreatePipe(&hReadPipeCmd,&hWritePipeCmd,&sa,0); 96 CreatePipe(&hReadPipeShell,&hWritePipeShell,&sa,0); 97 98 GetStartupInfo(&si); 99 si.cb = sizeof(STARTUPINFO); 100 si.wShowWindow = SW_HIDE; 101 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; 102 si.hStdInput = hReadPipeShell; 103 si.hStdOutput = si.hStdError = hWritePipeCmd; 104 //找到cmd的絕對路徑 105 char strShellPath[256]="\x00"; 106 GetSystemDirectory(strShellPath, 256); 107 strcat(strShellPath,"\\cmd.exe"); 108 //建立cmd程序 109 if (!CreateProcess(strShellPath,NULL, NULL, NULL,TRUE,NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi)) 110 { 111 //printf("CreateProcess Error!\n"); 112 CloseHandle(hWritePipeCmd); 113 CloseHandle(hReadPipeShell); 114 //initPipeSuccess = FALSE; 115 return; 116 } 117 hProcessHandle = pi.hProcess; 118 //initPipeSuccess = TRUE; 119 }