I'm looking for a way to detect the # of running processes that has same process name.
In example, I ran notepad three times.
notepad.exe
notepad.exe
notepad.exe
So it will return 3.
I currently have these code to detect a running process, but not counting its running process quantity.
#include <iostream> #include <windows.h> #include <tlhelp32.h> #include <tchar.h> bool IsProcessRunning(const char *ProcessName); int main() { char *notepadRunning = (IsProcessRunning("notepad.exe")) ? "Yes" : "No"; std::cout << "Is Notepad running? " << notepadRunning; return 0; } bool IsProcessRunning(const char *ProcessName) { PROCESSENTRY32 pe32 = { sizeof(PROCESSENTRY32) }; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(Process32First(hSnapshot, &pe32)) { do { if(_tcsicmp(pe32.szExeFile, ProcessName) == 0) { CloseHandle(hSnapshot); return true; } } while(Process32Next(hSnapshot, &pe32)); } CloseHandle(hSnapshot); return false; }
Any kind of help would be appreciated 🙂
Thanks.
Best Answer
You are using the correct API, namely CreateToolhelp32Snapshot, Process32First and Process32Next. And as you are doing, you should be using the szExeFile member from the struct PROCESSENTRY32.
You are returning from your function when you find a match currently though. Instead you should be incrementing a counter and NOT returning. And return an int with the process count instead of a bool. Also be sure not to do CloseHandle(hSnapshot); until the end of the function after you have the count.
Also make sure to first acquire the privilege
SeDebugPrivilege
before enumerating, that way you will get all processes across all sessions and users.To acquire the privilege so you get all sessions:
Where acquirePrivilegeByName is defined as: