Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect win32 process creation/termination in c++

I know that to receive notifications about Win32 process creation or termination we might implement a NT kernel-mode driver using the APIs PsSetCreateProcessNotifyRoutine() that offers the ability to register system-wide callback function which is called by OS each time when a new process starts, exits or is terminated.

Is this possible without creating a NT kernel-mode driver, only using Win32 API functions using c++? Not using the basic solution of a infinite cycle querying the list of active process of course.

Is there any library or win32 API that provides the same functionality (system wide callback, asynchronous events)?

like image 411
Nuno Avatar asked Aug 24 '10 11:08

Nuno


2 Answers

WMI is great and it works with process names too. Although if you need to track process termination the more lightweight and easier way is the following:

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 will call WaitOrTimerCallback once the process terminated.

like image 83
Anton K Avatar answered Nov 07 '22 05:11

Anton K


The only thing I could think of is WMI, not sure if it provides a process creation callback, but it might be worth looking into.

like image 14
Anders Avatar answered Nov 07 '22 04:11

Anders