0%

C++执行命令行、获取命令行输出

  1. 老方法,使用_popen
  2. 使用CreateProcess配合管道输出
  3. 时间对比

老方法,使用_popen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::string GetCmdResult(const std::string& cmd)
{
char buf[1024] = { 0 };
FILE* pf = _popen(cmd.c_str(), "r");
if (nullptr == pf)
{
OutputDebugString("open pipe failed");
return "";
}

std::string ret;
while (fgets(buf, sizeof(buf), pf))
{
ret += buf;
}

_pclose(pf);
return ret;
}

使用CreateProcess配合管道输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
std::string GetCmdResult(const std::string& cmd)
{
// 创建读写管道
SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
HANDLE hReadPipe, hWritePipe;
if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0))
{
OutputDebugString("管道创建失败!");
return "";
}

// 创建进程监控
BOOL ret = FALSE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(STARTUPINFO));
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
si.cb = sizeof(STARTUPINFO);
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = NULL;
si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;

ret = CreateProcess(NULL, const_cast<char*>(cmd.c_str()), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);

if (ret)
{
CloseHandle(hWritePipe);

std::string resStr;
char pBuf[BUFFER_SIZE] = { 0 };
DWORD readSize = 0;
while (ReadFile(hReadPipe, pBuf, BUFFER_SIZE, &readSize, NULL))
{
resStr += pBuf;
ZeroMemory(pBuf, BUFFER_SIZE);
}
CloseHandle(hReadPipe);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

return resStr;
}
else
{
CloseHandle(hWritePipe);
CloseHandle(hReadPipe);
return "";
}
}

时间对比

  • _popen: 350ms左右
  • CreateProcess: 50ms左右