C++调用命令行执行语句

Talk is cheap. Show me the code.

RunCmdLine.h

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
55
56
57
#include <Windows.h>
#include <iostream>

inline void KillProcessById(DWORD pid)
{
HANDLE hnd;
hnd = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, TRUE, pid);
TerminateProcess(hnd, 0);
}

inline int RunCmdLine(char* command, int ms)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.wShowWindow = SW_SHOW; // Use 'SW_HIDE' for not show window
si.dwFlags = STARTF_USESHOWWINDOW;

ZeroMemory(&pi, sizeof(pi));

if (!CreateProcess(
NULL, // No module name (use command line)
command, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Use 'CREATE_NO_WINDOW' for not show window
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
std::cerr << "CreateProcess failed: " + GetLastError() << std::endl;
return -2;
}

// Wait until child process exits.
if (ms == 0)
{
WaitForSingleObject(pi.hProcess, INFINITE);
}
else
{
DWORD rtn = WaitForSingleObject(pi.hProcess, ms);
if (rtn == WAIT_TIMEOUT)
{
KillProcessById(pi.dwProcessId);
}
}
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}

Usage

1
2
3
4
5
6
7
#include <string>
#include "RunCmdLine.h"

std::string cmd = colmapPath + " mapper --database_path " + database_name +
" --image_path " + images_name + " --output_path " + sparse_name;

RunCmdLine((char*)cmd.c_str(), 0);