Detecting Win32 Process Creation and Termination in C
Implementing a kernel-mode driver using the PsSetCreateProcessNotifyRoutine() API is a common method to receive notifications about Win32 process creation or termination. However, is there an alternative approach that utilizes Win32 API functions in C ?
Win32 API Limitations
Querying the list of active processes in an infinite loop is not an ideal solution due to its high resource consumption. Unfortunately, there are no native Win32 API functions that provide the same full functionality as the kernel-mode driver approach.
Windows Management Instrumentation (WMI)
WMI offers a potential solution for monitoring process events. It can track the creation and termination of processes based on specific criteria, such as process name. However, WMI may involve higher overhead compared to kernel-mode drivers.
Alternative Approach Using WaitOrTimerCallback
If tracking process termination is the primary goal, a more lightweight and efficient approach is available:
VOID CALLBACK WaitOrTimerCallback( _In_ PVOID lpParameter, _In_ BOOLEAN TimerOrWaitFired ) { MessageBox(0, L"The process has exited.", L"INFO", MB_OK); return; } DWORD dwProcessID = 1234; HANDLE hProcHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessID); HANDLE hNewHandle; RegisterWaitForSingleObject(&hNewHandle, hProcHandle, WaitOrTimerCallback, NULL, INFINITE, WT_EXECUTEONLYONCE);
This code registers a callback function using RegisterWaitForSingleObject(). Once the process identified by hProcHandle terminates, the registered callback will be executed, calling the WaitOrTimerCallback function and displaying a message box notification.
The above is the detailed content of Can Process Creation and Termination be Monitored in User Mode with Win32 APIs?. For more information, please follow other related articles on the PHP Chinese website!