目的
调用命令行程序,返回结果。
思路
把命令行结果输入到管道中,exe的输出信息都存在了strOutput这个变量里。
实现代码
CString strCmd = L"yara64.exe C:\Users\Windows32\Downloads\yara-master\yara-master\windows\vs2017\x64\Debug\yara.txt ";//cmd命令
strCmd = strCmd + pid;
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL; //使用系统默认的安全描述符
sa.bInheritHandle = TRUE; //创建的进程继承句柄
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) //创建匿名管道
{
MessageBox(L"CreatePipe Failed!", L"提示", MB_OK | MB_ICONWARNING);
return 0;
}
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;
if (!CreateProcess(NULL, strCmd.GetBuffer(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi)) //创建子进程
{
MessageBox(L"CreateProcess Failed!", L"提示", MB_OK | MB_ICONWARNING);
return 0;
}
CloseHandle(hWrite); //关闭管道句柄
char buffer[4096] = { 0 };
CString strOutput;
DWORD bytesRead;
while (true)
{
if (ReadFile(hRead, buffer, 4095, &bytesRead, NULL) == NULL) //读取管道
break;
strOutput += buffer;
UpdateWindow();
Sleep(100);
}
CloseHandle(hRead);