C++, How to determine if a Windows Process is running? - c++

This is concerning Windows XP processes.
I have a process running, let's call it Process1. Process1 creates a new process, Process2, and saves its id.
Now, at some point Process1 wants Process2 to do something, so it first needs to make sure that Process2 is still alive and that the user has not not killed it.
How can I check that this process is still running?
Since I created it, I have the Process ID, I would think there is some library function along the lines of IsProcessIDValid( id ) but I can't find it on MSDN

You can use GetExitCodeProcess. It will return STILL_ACTIVE (259) if the process is still running (or if it happened to exit with that exit code :( ).

The process handle will be signaled if it exits.
So the following will work (error handling removed for brevity):
BOOL IsProcessRunning(DWORD pid)
{
HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);
DWORD ret = WaitForSingleObject(process, 0);
CloseHandle(process);
return ret == WAIT_TIMEOUT;
}
Note that process ID's can be recycled - it's better to cache the handle that is returned from the CreateProcess call.
You can also use the threadpool API's (SetThreadpoolWait on Vista+, RegisterWaitForSingleObject on older platforms) to receive a callback when the process exits.
EDIT: I missed the "want to do something to the process" part of the original question. You can use this technique if it is ok to have potentially stale data for some small window or if you want to fail an operation without even attempting it. You will still have to handle the case where the action fails because the process has exited.

#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
/*!
\brief Check if a process is running
\param [in] processName Name of process to check if is running
\returns \c True if the process is running, or \c False if the process is not running
*/
bool IsProcessRunning(const wchar_t *processName)
{
bool exists = false;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry))
while (Process32Next(snapshot, &entry))
if (!wcsicmp(entry.szExeFile, processName))
exists = true;
CloseHandle(snapshot);
return exists;
}

The solution provided by #user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
bool IsProcessRunning(const TCHAR* const executableName) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) {
CloseHandle(snapshot);
return false;
}
do {
if (!_tcsicmp(entry.szExeFile, executableName)) {
CloseHandle(snapshot);
return true;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return false;
}

I found this today, it is from 2003. It finds a process by name, you don't even need the pid.
\#include windows.h
\#include tlhelp32.h
\#include iostream.h
int FIND_PROC_BY_NAME(const char *);
int main(int argc, char *argv[])
{
// Check whether a process is currently running, or not
char szName[100]="notepad.exe"; // Name of process to find
int isRunning;
isRunning=FIND_PROC_BY_NAME(szName);
// Note: isRunning=0 means process not found, =1 means yes, it is found in memor
return isRunning;
}
int FIND_PROC_BY_NAME(const char *szToFind)
// Created: 12/29/2000 (RK)
// Last modified: 6/16/2003 (RK)
// Please report any problems or bugs to kochhar#physiology.wisc.edu
// The latest version of this routine can be found at:
// http://www.neurophys.wisc.edu/ravi/software/killproc/
// Check whether the process "szToFind" is currently running in memory
// This works for Win/95/98/ME and also Win/NT/2000/XP
// The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE"
// will both work (for szToFind)
// Return codes are as follows:
// 0 = Process was not found
// 1 = Process was found
// 605 = Unable to search for process
// 606 = Unable to identify system type
// 607 = Unsupported OS
// 632 = Process name is invalid
// Change history:
// 3/10/2002 - Fixed memory leak in some cases (hSnapShot and
// and hSnapShotm were not being closed sometimes)
// 6/13/2003 - Removed iFound (was not being used, as pointed out
// by John Emmas)
{
BOOL bResult,bResultm;
DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
DWORD iCbneeded,i;
char szName[MAX_PATH],szToFindUpper[MAX_PATH];
HANDLE hProc,hSnapShot,hSnapShotm;
OSVERSIONINFO osvi;
HINSTANCE hInstLib;
int iLen,iLenP,indx;
HMODULE hMod;
PROCESSENTRY32 procentry;
MODULEENTRY32 modentry;
// PSAPI Function Pointers.
BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
DWORD, LPDWORD );
DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
LPTSTR, DWORD );
// ToolHelp Function Pointers.
HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;
// Transfer Process name into "szToFindUpper" and
// convert it to upper case
iLenP=strlen(szToFind);
if(iLenP<1 || iLenP>MAX_PATH) return 632;
for(indx=0;indx<iLenP;indx++)
szToFindUpper[indx]=toupper(szToFind[indx]);
szToFindUpper[iLenP]=0;
// First check what version of Windows we're in
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
bResult=GetVersionEx(&osvi);
if(!bResult) // Unable to identify system version
return 606;
// At Present we only support Win/NT/2000 or Win/9x/ME
if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
(osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
return 607;
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
// Win/NT or 2000 or XP
// Load library and get the procedures explicitly. We do
// this so that we don't have to worry about modules using
// this code failing to load under Windows 95, because
// it can't resolve references to the PSAPI.DLL.
hInstLib = LoadLibraryA("PSAPI.DLL");
if(hInstLib == NULL)
return 605;
// Get procedure addresses.
lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
GetProcAddress( hInstLib, "EnumProcesses" ) ;
lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
DWORD, LPDWORD)) GetProcAddress( hInstLib,
"EnumProcessModules" ) ;
lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
LPTSTR, DWORD )) GetProcAddress( hInstLib,
"GetModuleBaseNameA" ) ;
if( lpfEnumProcesses == NULL ||
lpfEnumProcessModules == NULL ||
lpfGetModuleBaseName == NULL)
{
FreeLibrary(hInstLib);
return 605;
}
bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
if(!bResult)
{
// Unable to get process list, EnumProcesses failed
FreeLibrary(hInstLib);
return 605;
}
// How many processes are there?
iNumProc=iCbneeded/sizeof(DWORD);
// Get and match the name of each process
for(i=0;i<iNumProc;i++)
{
// Get the (module) name for this process
strcpy(szName,"Unknown");
// First, get a handle to the process
hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
aiPID[i]);
// Now, get the process name
if(hProc)
{
if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
{
iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
}
}
CloseHandle(hProc);
// Match regardless of lower or upper case
if(strcmp(_strupr(szName),szToFindUpper)==0)
{
// Process found
FreeLibrary(hInstLib);
return 1;
}
}
}
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
{
// Win/95 or 98 or ME
hInstLib = LoadLibraryA("Kernel32.DLL");
if( hInstLib == NULL )
return FALSE ;
// Get procedure addresses.
// We are linking to these functions of Kernel32
// explicitly, because otherwise a module using
// this code would fail to load under Windows NT,
// which does not have the Toolhelp32
// functions in the Kernel 32.
lpfCreateToolhelp32Snapshot=
(HANDLE(WINAPI *)(DWORD,DWORD))
GetProcAddress( hInstLib,
"CreateToolhelp32Snapshot" ) ;
lpfProcess32First=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32First" ) ;
lpfProcess32Next=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32Next" ) ;
lpfModule32First=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32First" ) ;
lpfModule32Next=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32Next" ) ;
if( lpfProcess32Next == NULL ||
lpfProcess32First == NULL ||
lpfModule32Next == NULL ||
lpfModule32First == NULL ||
lpfCreateToolhelp32Snapshot == NULL )
{
FreeLibrary(hInstLib);
return 605;
}
// The Process32.. and Module32.. routines return names in all uppercase
// Get a handle to a Toolhelp snapshot of all the systems processes.
hSnapShot = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS, 0 ) ;
if( hSnapShot == INVALID_HANDLE_VALUE )
{
FreeLibrary(hInstLib);
return 605;
}
// Get the first process' information.
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult=lpfProcess32First(hSnapShot,&procentry);
// While there are processes, keep looping and checking.
while(bResult)
{
// Get a handle to a Toolhelp snapshot of this process.
hSnapShotm = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
if( hSnapShotm == INVALID_HANDLE_VALUE )
{
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 605;
}
// Get the module list for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32First(hSnapShotm,&modentry);
// While there are modules, keep looping and checking
while(bResultm)
{
if(strcmp(modentry.szModule,szToFindUpper)==0)
{
// Process found
CloseHandle(hSnapShotm);
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 1;
}
else
{ // Look for next modules for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32Next(hSnapShotm,&modentry);
}
}
//Keep looking
CloseHandle(hSnapShotm);
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult = lpfProcess32Next(hSnapShot,&procentry);
}
CloseHandle(hSnapShot);
}
FreeLibrary(hInstLib);
return 0;
}

Another way of monitoring a child-process is to create a worker thread that will :
call CreateProcess()
call WaitForSingleObject() // the worker thread will now wait till the child-process finishes execution. it's possible to grab the return code (from the main() function) too.

You can never check and see if a process is running, you can only check to see if a process was running at some point in the recent past. A process is an entity that is not controlled by your application and can exit at any moment in time. There is no way to guaranteed that a process will not exit in between the check to see if it's running and the corresponding action.
The best approach is to just do the action required and catch the exception that would be thrown if the process was not running.

call EnumProcesses() and check if the PID is in the list.
http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx

JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.
You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.
Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.

You may find if a process (given its name or PID) is running or not by iterating over the running processes simply by taking a snapshot of running processes via CreateToolhelp32Snapshot, and by using Process32First and Process32Next calls on that snapshot.
Then you may use th32ProcessID field or szExeFile field of the resulting PROCESSENTRY32 struct depending on whether you want to search by PID or executable name. A simple implementation can be found here.

While writing a monitoring tool, i took a slightly different approach.
It felt a bit wasteful to spin up an extra thread just to use WaitForSingleObject or even the RegisterWaitForSingleObject (which does that for you). Since in my case i don't need to know the exact instant a process has closed, just that it indeed HAS closed.
I'm using the GetProcessTimes() instead:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx
GetProcessTimes() will return a FILETIME struct for the process's ExitTime only if the process has actually exited. So is just a matter of checking if the ExitTime struct is populated and if the time isn't 0;
This solution SHOULD account the case where a process has been killed but it's PID was reused by another process. GetProcessTimes needs a handle to the process, not the PID. So the OS should know that the handle is to a process that was running at some point, but not any more, and give you the exit time.
Relying on the ExitCode felt dirty :/

This is a solution that I've used in the past. Although the example here is in VB.net - I've used this technique with c and c++. It bypasses all the issues with Process IDs & Process handles, and return codes. Windows is very faithful in releasing the mutex no matter how Process2 is terminated. I hope it is helpful to someone...
**PROCESS1 :-**
Randomize()
mutexname = "myprocess" & Mid(Format(CDbl(Long.MaxValue) * Rnd(), "00000000000000000000"), 1, 16)
hnd = CreateMutex(0, False, mutexname)
' pass this name to Process2
File.WriteAllText("mutexname.txt", mutexname)
<start Process2>
<wait for Process2 to start>
pr = WaitForSingleObject(hnd, 0)
ReleaseMutex(hnd)
If pr = WAIT_OBJECT_0 Then
<Process2 not running>
Else
<Process2 is running>
End If
...
CloseHandle(hnd)
EXIT
**PROCESS2 :-**
mutexname = File.ReadAllText("mutexname.txt")
hnd = OpenMutex(MUTEX_ALL_ACCESS Or SYNCHRONIZE, True, mutexname)
...
ReleaseMutex(hnd)
CloseHandle(hnd)
EXIT

char tmp[200] = "taskkill /f /im chrome.exe && \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"
while (1)
{
FILE* f;
f = _popen("tasklist", "r");
char b[512];
bzero(b, 512);
while (fgets(b, 512, f) != NULL)
{
if (strncmp(b, "chrome.exe", 8) == 0)
{
printf("Chrome running!\n");
system(tmp);
}
else
{
printf("Chrome NOT running!\n");
}
}
Sleep(1000);
}

Related

How to detect which application execute my program in Delphi? [duplicate]

I'm currently passing the pid on the command line to the child, but is there a way to do this in the Win32 API? Alternatively, can someone alleviate my fear that the pid I'm passing might belong to another process after some time if the parent has died?
Just in case anyone else runs across this question and is looking for a code sample, I had to do this recently for a Python library project I'm working on. Here's the test/sample code I came up with:
#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
int main(int argc, char *argv[])
{
int pid = -1;
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
//assume first arg is the PID to get the PPID for, or use own PID
if (argc > 1) {
pid = atoi(argv[1]);
} else {
pid = GetCurrentProcessId();
}
if( Process32First(h, &pe)) {
do {
if (pe.th32ProcessID == pid) {
printf("PID: %i; PPID: %i\n", pid, pe.th32ParentProcessID);
}
} while( Process32Next(h, &pe));
}
CloseHandle(h);
}
A better way to do this is to call DuplicateHandle() to create an inheritable duplicate of your process handle. Then create the child process and pass the handle value on the command line. Close the duplicated handle in the parent process. When the child's done, it will need to Close its copy as well.
ULONG_PTR GetParentProcessId() // By Napalm # NetCore2K
{
ULONG_PTR pbi[6];
ULONG ulSize = 0;
LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength);
*(FARPROC *)&NtQueryInformationProcess =
GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess");
if(NtQueryInformationProcess){
if(NtQueryInformationProcess(GetCurrentProcess(), 0,
&pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi))
return pbi[5];
}
return (ULONG_PTR)-1;
}
Notice that if the parent process terminates it is very possible and even likely that the PID will be reused for another process. This is standard windows operation.
So to be sure, once you receive the id of the parent and are sure it is really your parent you should open a handle to it and use that.
"Alternatively, can someone alleviate my fear that the pid I'm passing
might belong to another process after some time if the parent has
died?"
Yes, the PID can be reused. Unlike UNIX, Windows does not maintain a strong parent-child relationship tree.

CreateToolhelp32Snapshot: INVALID_HANDLE_VALUE (ERROR_PARTIAL_COPY)

This code is running in a 64-bit application. The target application is 32-bit.
Every time I run this code, CreateToolhelp32Snapshot() returns INVALID_HANDLE_VALUE and then GetLastError() returns ERROR_PARTIAL_COPY. So it skips the loop and returns false.
BOOL HookInjector::InjectIntoProcess(DWORD pID)
{
//Get Handle to Remote Process
HANDLE Proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
....
//Check to see if 64-bit or 32-bit application
IsWow64Process(Proc, &isWow64);
size_t szCurProc = sizeof(void*); //returns 8
if (isWow64)
{
__debugbreak();
//Get list of all Modules associated with the Process
HANDLE hProc32Module;
do {
hProc32Module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32, pID);
}
while ((hProc32Module == INVALID_HANDLE_VALUE) && (GetLastError() == ERROR_BAD_LENGTH));
if (hProc32Module == INVALID_HANDLE_VALUE) {
__debugbreak();
DWORD err = GetLastError(); //just to see the error code which is 0x12b
return false;
}
//Find the module for Kernel.dll and get the base address of it
MODULEENTRY32 entryModule;
entryModule.dwSize = sizeof(MODULEENTRY32);
BOOL isGetModuleSuccess = Module32First(hProc32Module, &entryModule);
DWORD errEndofList = GetLastError();
BOOL isSuccessful = false;
while (errEndofList != ERROR_NO_MORE_FILES && isGetModuleSuccess)
{
if (_tcscmp(entryModule.szModule, KERNEL32_DLL)){
isSuccessful = true;
break;
}
isGetModuleSuccess = Module32Next(hProc32Module, &entryModule);
errEndofList = GetLastError();
}
if (!isSuccessful)
{
__debugbreak();
CloseHandle(hProc32Module);
return false;
}
//Get handle for Kernel.dll module
hKernel32 = entryModule.hModule;
CloseHandle(hProc32Module);
}
else
{
....
According to the documentation, CreateToolhelp32Snapshot() only fails with ERROR_PARTIAL_COPY when CreateToolhelp32Snapshot() is called by a 32bit process trying to access a 64bit process:
If the specified process is a 64-bit process and the caller is a 32-bit process, this function fails and the last error code is ERROR_PARTIAL_COPY (299).
Make sure your app really is compiled for 64bit to begin with. TH32CS_SNAPMODULE32 only makes sense to use when CreateToolhelp32Snapshot() is being called in a 64bit process:
TH32CS_SNAPMODULE32
0x00000010
Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit process.
You are also not taking into account that GetLastError() is only updated when API functions fail, unless documented otherwise. Your loops are assuming that GetLastError() is updated after every API call, that is simply not true.
Try something more like this instead:
BOOL HookInjector::InjectIntoProcess(DWORD pID)
{
//Get Handle to Remote Process
HANDLE Proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
....
DWORD dwFlag;
#ifdef _WIN64
//Check if Remote Process is a 32-bit application
BOOL isWow64 = FALSE;
IsWow64Process(Proc, &isWow64);
if (!isWow64) return false;
// TH32CS_SNAPMODULE32 includes 32bit modules when used by a 64bit process...
dwFlag = TH32CS_SNAPMODULE32;
#else
// TH32CS_SNAPMODULE includes 32bit modules when used by a 32bit process...
dwFlag = TH32CS_SNAPMODULE;
#endif
__debugbreak();
//Get list of all Modules associated with the Process
HANDLE hProc32Module;
do {
hProc32Module = CreateToolhelp32Snapshot(dwFlag, pID);
}
while ((hProc32Module == INVALID_HANDLE_VALUE) && (GetLastError() == ERROR_BAD_LENGTH));
if (hProc32Module == INVALID_HANDLE_VALUE) {
__debugbreak();
return false;
}
//Find the module for Kernel.dll and get the base address of it
hKernel32 = NULL;
MODULEENTRY32 entryModule = {0};
entryModule.dwSize = sizeof(MODULEENTRY32);
BOOL isGetModuleSuccess = Module32First(hProc32Module, &entryModule);
while (isGetModuleSuccess) {
if (_tcscmp(entryModule.szModule, KERNEL32_DLL)) {
hKernel32 = entryModule.hModule;
break;
}
isGetModuleSuccess = Module32Next(hProc32Module, &entryModule);
}
if (!hKernel32) {
__debugbreak();
CloseHandle(hProc32Module);
return false;
}
CloseHandle(hProc32Module);
....
}
According to the documentation, CreateToolhelp32Snapshot() only fails with ERROR_PARTIAL_COPY when CreateToolhelp32Snapshot() is called by a 32bit process trying to access a 64bit process:
If the specified process is a 64-bit process and the caller is a 32-bit process, this function fails and the last error code is ERROR_PARTIAL_COPY (299).
This is plain wrong as you could have deduced from the excerpt you posted. Where does it say it ONLY fails with ERROR_PARTIAL_COPY (299) when the caller is 32bit trying to access 64bit? It doesn't.
If the documentation would be complete, which it is not, then you would be right to assume that the stated behaviour is the only way to generate an ERROR_PARTIAL_COPY error code. Sadly the documentation is not complete.
For example if you start a process with the CREATE_SUSPENDED flag the CreateToolhelp32Snapshot API will set the error code to ERROR_PARTIAL_COPY when queried for modules regardless of the bitness of the host or target application. The reason it fails is because the DLLs aren't loaded until after the main thread is resumed and therefore the PebLdr pointer in the PEB structure is NULL.
Basically anything which prevents read of process memory (missing address in PEB, unmapped segment, etc.) can cause ERROR_PARTIAL_COPY as its description states:
ERROR_PARTIAL_COPY 299 (0x12B)
Only part of a ReadProcessMemory or WriteProcessMemory request was completed.

C++ How to Check if an Outlook Process is already running

I am new to C++ programming but I would like to know if there is an easy way to check if an Outlook Process is already running, or in other words check if Outlook is already open.
Can anyone show me, please?
Thanks
You can check the running instance of the outlook OLE:
static const bool isOutlookRunning()
{
CLSID clsid;
HRESULT hr = CLSIDFromProgID( _T("Outlook.Application"), &clsid );
if( hr != S_OK ) return false;
IUnknown *pUnknown = NULL;
hr = GetActiveObject( clsid, 0, &pUnknown );
return ( hr == S_OK );
}
This code will not work if the app from you invoke it is running in different user security context than Outlook.
Its better to check for the process name.
//////////////////////////////////////////////////////////////////////
// IsProcessRunning
//////////////////////////////////////////////////////////////////////
bool IsProcessRunning(string &strProcessFullPathName)
{
// Get the list of process identifiers.
DWORD dwProcesses[2048];
DWORD dwSizeNeeded = 0;
DWORD dwProcessesCount = 0;
if ( !EnumProcesses( dwProcesses, sizeof(dwProcesses), &dwSizeNeeded ) )
{
_dwLastErrorCode = GetLastError();
_strLastError = "EnumProcesses";
return false;
}
dwProcessesCount = dwSizeNeeded / sizeof(DWORD);
string strToCheck = strProcessFullPathName;
transform(strToCheck.begin(), strToCheck.end(), strToCheck.begin(), tolower);
for(int i=0; i<(int)dwProcessesCount; i++ )
{
if( dwProcesses[i] != 0 )
{
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcesses[i]);
if(hProcess)
{
HMODULE hModule = NULL;
dwSizeNeeded = 0;
char cName[MAX_PATH];
if(EnumProcessModules(hProcess, &hModule, sizeof(DWORD), &dwSizeNeeded) )
{
if(GetModuleFileNameEx(hProcess, hModule, cName, MAX_PATH ) != 0)
{
string strName(cName);
// Convert to LowerCase
transform(strName.begin(), strName.end(), strName.begin(), tolower);
if(strName == strToCheck)
{
CloseHandle(hProcess);
return true;
}
}
}
CloseHandle(hProcess);
}
}
}
return false;
}
I assume that you are using Windows as platform, since Outlook normally runs under a Windows OS.
For a simple check you can use the Windows API functions EnumProcesses() and GetModuleBaseName() to determine the executable filename of the running processes and check if the executable name is "outlook.exe". A reference for the functions can be found in the MSDN.
Be aware that the this check may fail if the user runs another program that is using the same executable filename as Outlook. Another trap with the provided solution might be the access rights a user needs for the specified API calls.
Improvements might be to check the version information in the executable file too by using GetFileVersionInfo().
You can use CreateToolhelp32Snapshot and iterate through the running processes. If you need to heck for Outlook again (say you need to poll for the process), then save the process ID and use OpenProcess (many times faster). More details are given in the answer to this question:
Check whether one specific process is running on windows with C++

How to catch quit message from another process?

I want to "listen" some other application and decide what to do when it has been terminated.
How?
Edit: The two programs are run on same computer, and i want to know when i close the other program. And then do action in the other program. I cant modify the other program code. I may or may not start the app B from app A. I could identify the app B by its full path to the exe.
As Abyx wrote, WaitForSingleObject (or possibly WaitForMulipleObjects) is the API function you need.
Create an event
Start a (worker) thread
Pass the event handle to the thread -> HANDLE1
Get handle for the process to be watched. See How can I get a process handle by its name in C++? -> HANDLE2
In your thread function call WaitForMulipleObjects and wait for the two handles.
If HANDLE2 fires, do whatever action you want... and possibly terminate the thread.
If HANDLE1 fires, leave the thread. This is for a graceful termination of your application: Before exiting the main (GUI) thread you set the event.
WaitForSingleObject(hProcess, INFINITE);
If you start yourself, the process which termination you want wait for, for example with respect of the CreateProcess, the waiting for the process end is very simple
WaitForSingleObject(pi.hProcess, INFINITE);
If the process, which termination you want wait for, is started before you should find the process id dwProcessId of the process and then do following
HANDLE hProcess = OpenProcess (SYNCHRONIZE, FALSE, dwProcessId);
WaitForSingleObject(hProcess, INFINITE);
The searching of the process id can be implemented in different ways depend on which information you know about the process and the knowledge how many instances of the process can be running simultaneously.
For example if you know the filename of the process which is currently running you can use EnumProcesses, OpenProcess and GetProcessImageFileName. Here is the corresponding code in a simplified form:
#include <Windows.h>
#include <stdio.h>
#include <tchar.h>
#include <Psapi.h>
#include <shlwapi.h>
#pragma comment (lib, "Psapi.lib")
#pragma comment (lib, "shlwapi.lib")
int _tmain (int argc, LPCTSTR argv[])
{
DWORD arProcessIds[1024], cbNeeded, i, dwStatus;
HANDLE hProcess = NULL;
LPCTSTR pszProcessName = NULL;
if (argc != 2) {
_tprintf (TEXT("USAGE:\n")
TEXT(" \"%s\" ExeName\n\n")
TEXT("Examples:\n")
TEXT(" \"%s\" TaskMgr.exe\n"),
argv[0], argv[0]);
return 1; // error
}
pszProcessName = argv[1];
if (!EnumProcesses (arProcessIds, sizeof(arProcessIds), &cbNeeded)) {
// here shold be allocated array dynamically
return 1; // error
}
for (i = 0; i < cbNeeded/sizeof(DWORD); i++ ) {
if (arProcessIds[i] != 0) {
TCHAR szFileName[MAX_PATH];
hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | SYNCHRONIZE, FALSE, arProcessIds[i]);
if (hProcess != NULL) {
dwStatus = GetProcessImageFileName (hProcess, szFileName, sizeof(szFileName)/sizeof(TCHAR));
if (dwStatus > 0 ) {
LPCTSTR pszFileName = PathFindFileName (szFileName);
//_tprintf(TEXT("Process: %s\n"),szFileName);
if (StrCmpI(pszFileName, pszProcessName) == 0) {
break;
}
}
CloseHandle (hProcess);
hProcess = NULL;
}
}
}
//hProcess = OpenProcess (SYNCHRONIZE, FALSE, dwProcessId);
if (hProcess == NULL) {
_tprintf(TEXT("The process \"%s\" is not found.\n"), pszProcessName);
return 1;
}
_tprintf(TEXT("Start waiting for the end of the process %s\n"), pszProcessName);
WaitForSingleObject(hProcess, INFINITE);
_tprintf(TEXT("The process is terminated"));
CloseHandle (hProcess);
return 0;
}
you can just get the process list from OS in intervals you want and take appropriate action

How to effectively kill a process in C++ (Win32)?

I am currently writing a very lightweight program so I have to use C++ since it is not bound to .NET framework which drastically increases size of the program.
I need to be able to terminate process and to do that I need to get a process handle. Unfortuanately I haven't figured how to do that yet.
P.S. I know that to kill a process you have to use TerminateProcess.
The following code works:
const auto explorer = OpenProcess(PROCESS_TERMINATE, false, process_id);
TerminateProcess(explorer, 1);
CloseHandle(explorer);
The PID you need for OpenProcess() is not normally easy to get a hold of. If all you got is a process name then you need to iterate the running processes on the machine. Do so with CreateToolhelp32Snapshot, followed by Process32First and loop with Process32Next. The PROCESSENTRY32.szExeFile gives you the process name (not path!), th32ProcessID gives you the PID.
The next consideration is that the process may appear more than once. And there's a chance that the same process name is used for very different programs. Like "Setup". If you don't just want to kill them all, you'll need to try to obtain some runtime info from them. Window caption bar text, perhaps. GetProcessImageFileName() can give you the path to the .exe. It uses the native kernel format, you'd need QueryDosDevice to map a disk drive device name to a drive letter.
The next consideration is the rights you ask for in OpenProcess(). You are unlikely to get PROCESS_ALL_ACCESS, all you need is PROCESS_TERMINATE. Although that's privileged as well. Ensure the account you use to run your program can obtain that right.
Rather than going through all that pain to kill a process with a known name, why not simply call out to "system" and ask the command-line to kill it?
For example,
int retval = ::_tsystem( _T("taskkill /F /T /IM MyProcess.exe") );
To get a handle to pass to TerminateProcess, use OpenProcess in combination with some other function like EnumProcesses.
Here is the full example for Visual Studio 2010 C++ project how to kill the process by the EXE file name.
In order to check it just run Internet Explorer and after this execute following code.
#include <iostream>
#include <string>
#include<tchar.h>
#include <process.h>
#include <windows.h>
#include <tlhelp32.h>
using namespace std;
// Forward declarations:
BOOL GetProcessList();
BOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode);
int main( void )
{
GetProcessList( );
return 0;
}
BOOL GetProcessList( )
{
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
DWORD dwPriorityClass;
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
return( FALSE );
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
if( !Process32First( hProcessSnap, &pe32 ) )
{
CloseHandle( hProcessSnap ); // clean the snapshot object
return( FALSE );
}
// Now walk the snapshot of processes
do
{
string str(pe32.szExeFile);
if(str == "iexplore.exe") // put the name of your process you want to kill
{
TerminateMyProcess(pe32.th32ProcessID, 1);
}
} while( Process32Next( hProcessSnap, &pe32 ) );
CloseHandle( hProcessSnap );
return( TRUE );
}
BOOL TerminateMyProcess(DWORD dwProcessId, UINT uExitCode)
{
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (hProcess == NULL)
return FALSE;
BOOL result = TerminateProcess(hProcess, uExitCode);
CloseHandle(hProcess);
return result;
}
Imagine in C# it looks like
using System;
using System.Collections.Generic;
using System.Text;
namespace MyProcessKiller
{
class Program
{
static void Main(string[] args)
{
foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
{
if (myProc.ProcessName == "iexplore")
{
myProc.Kill();
}
}
}
}
}
windows only
system("taskkill /f /im servicetokill.exe")
Here are some working sample codes to kill a process called "ShouldBeDead.exe":
// you will need these headers, and you also need to link to Psapi.lib
#include <tchar.h>
#include <psapi.h>
...
// first get all the process so that we can get the process id
DWORD processes[1024], count;
if( !EnumProcesses( processes, sizeof(processes), &count ) )
{
return false;
}
count /= sizeof(DWORD);
for(unsigned int i = 0; i < count; i++)
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
if(processes[i] != 0)
{
// remember to open with PROCESS_ALL_ACCESS, otherwise you will not be able to kill it
HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processes[i] );
if(NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if(EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
// find the process and kill it
if(strcmp(szProcessName, "ShouldBeDead.exe") == 0)
{
DWORD result = WAIT_OBJECT_0;
while(result == WAIT_OBJECT_0)
{
// use WaitForSingleObject to make sure it's dead
result = WaitForSingleObject(hProcess, 100);
TerminateProcess(hProcess, 0);
}
CloseHandle(hProcess);
}
}
}
}
}
CreateProcess and OpenProcess return process handles.
Here's some sample code to find a process by asking the system to list all processes and then searching the list for the process you want.
Task Killer using Modern C++
Below is the code I've created for my Terminator Program
//_____________________________________________
// |
// TheNexGen of Terminator (inclusion version) |
// ------------------------------------------- |
// |
// Add your Programs in the 'if' check as I've |
// listed below, and compile using c++17 flag |
// or higher |
//_____________________________________________|
#include <process.h>
#include <windows.h>
#include <tlhelp32.h>
#include <string_view>
using namespace std;
int main()
{
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32W pe32{ .dwSize = sizeof(PROCESSENTRY32) };
if (!Process32First(hProcessSnap, &pe32)) return CloseHandle(hProcessSnap), 0;
do
{
wstring_view str = pe32.szExeFile;
if
(
str == L"chrome.exe"
|| str == L"AAM Update Notifier.exe"
|| str == L"About.exe"
|| str == L"ActionCenterDownloader.exe"
|| str == L"adb.exe"
|| str == L"AdobeARM.exe"
)
{
if (HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, pe32.th32ProcessID))
{
TerminateProcess(hProcess, 1);
CloseHandle(hProcess);
}
}
}
while (Process32Next(hProcessSnap, &pe32));
CloseHandle(hProcessSnap);
}
Description
Increased Execution Speed 100x of the Code provided by #DmitryBoyko.