How does windows terminate processes?

574 views Asked by At

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.

2

There are 2 answers

0
lordjeb On BEST ANSWER

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.

0
Lukas Thomsen On

I think there is no way to postpone the termination of a process. Even stopping all threads of that process will not help since the killing of the process is done by the kernel.

Due to my own experience I assume that windows does the following on process termination:

  1. Mark the process to be terminated
  2. Terminate all threads of the process
  3. Clean up (free memory, release handles, ...)
  4. Terminate process

Once step 1. is done the process is doomed since the scheduler will not activate any of the threads of that process. Activating one of the threads may cause them to go berserk since the process is in a partly destroyed state (e.g. memory may be freed, handles destroyed, ...) which may cause serious trouble!

I don't think that there is a possibility to change that behavior without chaning parts of the kernel.

Side note: It would be an interresting thing to test if WaitForSingleObject(thread, ...) is signalled before WaitForSingleObject(process, ...).