Search code examples
windowswinapiprocesswin32-processwindows-kernel

How does windows terminate processes?


I am developing an application in windows which should run a code just before the process terminates. i am okay writing a kernel module to achieve this. but what are the functions that i should hook into ?

To get the notification about the termination of process i am doing this.

HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 1234);
DWORD wait = WaitForSingleObject(handle, INFINITE);
// Some block of code here that does the business logic.
handleProcessTermination();

My problem is the target process exits before my function handleProcessTermination() completes. i want a way to stop the exit of process and run my logic.


Solution

  • You should be able to create a kernel driver that calls PsSetCreateProcessNotifyRoutineEx to create a callback routine for when processes start/end. Your callback will be called "just before the last thread to exit the process is destroyed."

    This won't allow you to "stop" the process termination permanently, but does allow you to inject some code just prior to the process ending.