Do we need to use EnumProcesses and EnumProcessModules when terminating the process in C++?

  • Thread starter Thread starter bhavya internship
  • Start date Start date
B

bhavya internship

Guest
Hello All,

My utility application launches one of the below processes:
(one.exe, Two.exe, or Three.exe)

When terminating the process, I am calling the below functions.

In this function I am passing all the .exes into vector, enumerating the processes, Opening the process and then terminating the running process.

Do we need to use EnumProcesses and EnumProcessModules when terminating the process?

Can I directly do OpenProcess and do the TerminateProcess?
Below is the code snippet:

bool CMyUtility::terminateSDKProcess()
{
std::vector<LPCWSTR> l_vProcessName = { L"One.exe", L"Two.exe", L"Three.exe" };
STARTUPINFO si_;
PROCESS_INFORMATION pi_;
memset(&si_, 0, sizeof(si_));
memset(&pi_, 0, sizeof(pi_));
si_.cb = sizeof(si_);

BOOL l_MyAppRunning = IsProcessTerminating(l_vProcessName);
if (l_MyAppRunning)
{
return true;
}

return false;
}

bool IsProcessTerminating(std::vector<LPCWSTR>& f_processName)
{
const int l_maxNumProcesses = 1024;
std::unique_ptr<DWORD[]> l_dwaProcesses(new DWORD[l_maxNumProcesses]);
DWORD l_dwProcessNeeded;
DWORD l_dwProcess;
unsigned int i;
if (!EnumProcesses(l_dwaProcesses.get(), sizeof(DWORD) * l_maxNumProcesses, &l_dwProcessNeeded))
{
return false;
}
l_dwProcess = l_dwProcessNeeded / sizeof(DWORD);

if (l_dwProcess == l_maxNumProcesses)
{
}
for (i = 0; i < l_dwProcess; i++)
{
if (l_dwaProcesses != 0)
{
TCHAR l_szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE l_hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
l_dwaProcesses);
// Get the process name.
if (nullptr != l_hProcess)
{
HMODULE l_hMod;
DWORD l_dwProcessWant;
if (EnumProcessModules(l_hProcess, &l_hMod, sizeof(l_hMod),
&l_dwProcessWant))
{
GetModuleBaseName(l_hProcess, l_hMod, l_szProcessName,
sizeof(l_szProcessName) / sizeof(TCHAR));
}
CloseHandle(l_hProcess);
}
for (auto l_vName : f_processName)
{
if (_tcscmp(l_szProcessName, l_vName) == 0)
{
TerminateProcess(l_hProcess, 1);
CloseHandle(l_hProcess);
return true;
}
}
}
}
return false;
}

Continue reading...
 
Back
Top