在命令行中执行一个命令获取返回字符串

在MFC中经常需要在命令行中执行一个命令获取返回字符串

比如

查看网络是否正常:ping 192.168.1.1

查看本机端口:netstat -ano

 

注:请把bRet = CreateProcess(NULL,(LPTSTR )( LPCTSTR )strCmd,NULL,NULL,TRUE,0,NULL,NULL,&si,π); 

改成 bRet = CreateProcess(NULL,(LPTSTR )( LPCTSTR )strCmd,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi); 

/***************************************************************************** 函数:BOOL ExcuteCmd(const CString &strCmd,CString &strValue) 功能:执行一个命令提示符命令,成功则返回命令提示符的回显字符串 参数: 输入:1.strCmd:需要执行的命令 输出:1.strValue:执行成功则该变量返回命令提示符的回显字符串 返回值:成功返回TRUE 错误返回FALSE 有错误请查看调试窗口的输出 *****************************************************************************/ BOOL ExcuteCmd(const CString &strCmd,CString &strValue) { ASSERT(!strCmd.IsEmpty()); //定义最大的接收缓冲区大小 const DWORD MAX_BUFFER_SIZE = 10000; BOOL bRet = TRUE; DWORD dwRet = 0; SECURITY_ATTRIBUTES sa; HANDLE hReadPipe,hWritePipe; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; STARTUPINFO si; PROCESS_INFORMATION pi; try { bRet = CreatePipe(&hReadPipe,&hWritePipe,&sa,0); if(!bRet) { throw(_T("CreatePipe")); } si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWritePipe; si.hStdOutput = hWritePipe; si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; bRet = CreateProcess(NULL,(LPTSTR)(LPCTSTR)strCmd,NULL,NULL,TRUE,0,NULL,NULL,&si,π); if(!bRet) { throw(_T("CreateProcess")); } WaitForSingleObject(pi.hProcess,INFINITE); strValue.Empty(); bRet = ReadFile(hReadPipe,strValue.GetBuffer(MAX_BUFFER_SIZE),MAX_BUFFER_SIZE,&dwRet,NULL); strValue.ReleaseBuffer(dwRet); if(!bRet) { throw(_T("ReadFile")); } } catch(TCHAR c[]) { TRACE(_T("Error at %s Code:%d/n"),c,GetLastError()); bRet = FALSE; } CloseHandle(hWritePipe); CloseHandle(hReadPipe); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return bRet; }    

 

调用过程

CString strValue,strCmd; strCmd =_T("ping 127.0.0.1"); if(ExcuteCmd(strCmd,strValue)) { printf("%s/n",strValue); } strCmd =_T("netstat -ano"); if(ExcuteCmd(strCmd,strValue)) { printf("%s/n",strValue); }

你可能感兴趣的:(在命令行中执行一个命令获取返回字符串)