- 1 year ago
I want to get the PID of every process I've created in C++ and terminate each after specific time
To get the PID of every process you've created in C++ and terminate each after a specific time, you can use the Windows API functions CreateProcess
and TerminateProcess
. Here's a step-by-step guide on how to achieve this:
- Include the Necessary Headers:
cpp#include <Windows.h>
#include <iostream>
#include <vector>
- Define a Function to Create Processes:
cppbool CreateMyProcess(const char* applicationName, const char* commandLine, PROCESS_INFORMATION& processInfo)
{
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
// Create the process
return CreateProcess(applicationName, const_cast<char*>(commandLine), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo);
}
- Main Function to Create and Terminate Processes:
cppint main()
{
// List to store the process handles
std::vector<HANDLE> processHandles;
// Create and launch the processes
for (int i = 0; i < 5; ++i)
{
PROCESS_INFORMATION processInfo;
if (CreateMyProcess("C:\\path\\to\\your\\executable.exe", "arguments if any", processInfo))
{
// Store the process handle for later use
processHandles.push_back(processInfo.hProcess);
}
else
{
std::cout << "Failed to create process " << i << std::endl;
}
}
// Wait for the specified time (in milliseconds)
Sleep(5000);
// Terminate each process
for (HANDLE processHandle : processHandles)
{
TerminateProcess(processHandle, 0);
CloseHandle(processHandle);
}
return 0;
}
Note: Replace "C:\\path\\to\\your\\executable.exe"
with the actual path to the executable you want to run, and "arguments if any"
with any command-line arguments the executable may require.
Keep in mind that forcefully terminating processes with TerminateProcess
is generally not recommended, as it can lead to unexpected behavior and resource leaks. Consider gracefully asking each process to exit on its own if possible.
Additionally, you may need to include error handling and more robust logic in a real-world application to handle unexpected scenarios and manage resources properly.