Check if process is running

Feb 10, 2013 at 2:59pm
How can I check if a process is running in c++?
This is my current code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool isRunning(string pName)
{
	unsigned long aProcesses[1024], cbNeeded, cProcesses;
	if(!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
		return false;
 
	cProcesses = cbNeeded / sizeof(unsigned long);
	for(unsigned int i = 0; i < cProcesses; i++)
	{
		if(aProcesses[i] == 0)
			continue;
 
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, aProcesses[i]);
		char buffer[50];
		GetModuleBaseName(hProcess, 0, buffer, 50);
		CloseHandle(hProcess);
		if(pName == string(buffer))
			return true;
	}
	return false;
}

But that code always outputs "false".
Thanks.

EDIT: I fixed it! Here's my new code:
1
2
3
4
5
6
7
8
9
10
bool isRunning(LPCSTR pName)
{
	HWND hwnd; 
	hwnd = FindWindow(NULL, pName);
	if (hwnd != 0) { 
		return true;
	} else { 
		return false;
	} 
}
Last edited on Feb 12, 2013 at 10:24pm
Feb 12, 2013 at 7:33pm
If you have the process name, just call WaitForSingleObject with timeout zero and check the result. If you get a timeout return code, it's still running.
Feb 12, 2013 at 9:31pm
Your code works for me with "notepad.exe" for pName, but I've only tried it on my old, security lax Windows XP machine.

Is it the OpenProcess call that's failing? You could try checking the value of hProcess and handling the error.

Or the EnumProcesses call?

Andy

PS Once you have the handle to the process you're interested in, you can call GetExitCodeProcess. It will returns STILL_ACTIVE if the process is still running.

GetExitCodeProcess function (Windows)
http://msdn.microsoft.com/en-gb/library/windows/desktop/ms683189%28v=vs.85%29.aspx
Topic archived. No new replies allowed.