执行CMD命令并获取输出

c++

Posted by YiMiTuMi on November 22, 2022

执行CMD命令并获取输出

pszCmd执行的cmd命令, strReturnInfo返回的结果

BOOL ExeCmdForbidden(wstring pszCmd, wstring &strReturnInfo)
{
	SECURITY_ATTRIBUTES sa;
	wstring wstrCmd = pszCmd;
	HANDLE hRead = NULL;
	HANDLE hWrite = NULL;

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	//创建命名管道
	if (!CreatePipe(&hRead,&hWrite,&sa,0)) 
	{
		//MessageBox("Error On CreatePipe()");
		return FALSE;
	}
	
	//设置命令行参数
	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,
		(LPWSTR)wstrCmd.c_str(),
		NULL,
		NULL,
		TRUE,
		NULL,
		NULL,
		NULL,
		&si,
		&pi))
	{
		int iError = GetLastError();
		//LOGERRW(L" security policy Cmd CreateProcess : %d", iError);

		CloseHandle(hWrite);
		return FALSE;
	}

	// 等待进程执行
	//DWORD dwRet = WaitForSingleObject( pi.hProcess, INFINITE );

	CloseHandle(hWrite);

	//这里决定是否要等整个命令执行完,如ping等耗时较多的命令.
	/*if(WaitForSingleObject(pi.hProcess, INFINITE)==WAIT_FAILED)
	{
		//MessageBox("Failed!");
		return FALSE;
	}*/

	char buffer[4096] ={0} ;
	DWORD bytesRead;
	wstring strResult= L"";

	while(1)
	{
		memset(buffer,0,4096);
		if(ReadFile(hRead,buffer,4096,&bytesRead,NULL) != NULL)//从命名管道中读取数据
		{
			strResult += buffer;
		}
		else
		{
			break;
		}
	}


	strReturnInfo = strResult;

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	return TRUE;
}