- 1 year ago
Execute a command line process with C++ and gracefully close on Windows 10
To execute a command-line process with C++ and gracefully close it on Windows 10, you can use the CreateProcess
function from the Windows API. Here's an example of how you can achieve this:
cpp#include <Windows.h>
#include <iostream>
int main()
{
// Command to execute
LPCSTR command = "ping -n 10 127.0.0.1";
// Create process variables
STARTUPINFO si;
PROCESS_INFORMATION pi;
// Initialize startup info
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
// Create the process
if (!CreateProcess(NULL, const_cast<LPSTR>(command), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
std::cout << "Failed to create process. Error code: " << GetLastError() << std::endl;
return 1;
}
// Wait for the process to exit
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
In this example, we use the CreateProcess
function to create the process and WaitForSingleObject
to wait for it to exit. The process is created with the NULL
value for the process handle and thread handle inheritance, indicating that the new process does not inherit the handles from the calling process. Once the process has exited, we close the process and thread handles using CloseHandle
.
Note that you may need to adjust the command to the specific command you want to execute. Also, ensure that you have the necessary include and library files linked correctly in your project settings.
By using the CreateProcess
function and properly closing the process and thread handles, you can execute a command-line process with C++ and gracefully close it on Windows 10.