编程过程中我们可能需要用到cmd命令辅助我们快速实现某些功能,下面的代码将运行cmd命令并且获取返回数据
#include <string>
#include <vector>
#include <shlobj.h>
#define RunCmdWaitTimeout (20 * 1000)
std::string RunCmdWaitReturn(const std::string& strCmd, int dwMilliseconds = RunCmdWaitTimeout)
{
SECURITY_ATTRIBUTES sa = { 0 };
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
STARTUPINFOA si = { 0 };
PROCESS_INFORMATION pi = { 0 };
std::string tempCmd;
LPSTR cmdLine = NULL;
std::vector<char> buffer(4096);
DWORD bytesRead = 0;
std::string output;
HANDLE hRead = NULL, hWrite = NULL;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
printf("CreatePipe failed (%d).\n", GetLastError());
goto Exit0;
}
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE; // 隐藏窗口
si.hStdOutput = hWrite;
si.hStdError = hWrite;
tempCmd = std::string(strCmd.begin(), strCmd.end());
cmdLine = &tempCmd[0];
if (!CreateProcessA(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
printf("CreateProcess failed (%d).\n", GetLastError());
goto Exit0;
}
if (hWrite)
{
CloseHandle(hWrite);
hWrite = NULL;
}
// 读取子进程的输出
while (true) {
if (!ReadFile(hRead, &buffer[0], buffer.size(), &bytesRead, NULL) || bytesRead == 0) {
if (GetLastError() == ERROR_BROKEN_PIPE)
break;
else
printf("ReadFile failed (%d).\n", GetLastError());
}
output.append(&buffer[0], bytesRead);
}
// 等待子进程退出
if (pi.hProcess)
WaitForSingleObject(pi.hProcess, dwMilliseconds);
Exit0:
// 关闭进程和线程句柄
if (pi.hThread)
CloseHandle(pi.hThread);
if (pi.hProcess)
CloseHandle(pi.hProcess);
if (hRead)
CloseHandle(hRead);
if (hWrite)
CloseHandle(hWrite);
return output;
}
int mian()
{
auto strResult= RunCmdWaitReturn("ping -n 1 127.0.0.1");
}
其中RunCmdWaitTimeout是执行命令默认的等待时间
直接调用RunCmdWaitReturn我们可以看到返回值strResult值如下:
正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
127.0.0.1 的 Ping 统计信息:
数据包: 已发送 = 1,已接收 = 1,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms
如果想执行PowerShell命令可以查看另外一篇文章