How does windows terminate processes? - windows

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.

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.

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:
Mark the process to be terminated
Terminate all threads of the process
Clean up (free memory, release handles, ...)
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, ...).

Related

Prevent WaitForSingleObject from hanging on a named semaphore when other process is terminated?

When using a globally named mutex to synchronize across two processes, and one of the two processes are killed (say in Task Manager, or due to a fault), the other process returns from WaitForSingleObject() with the appropriate error code and can continue.
When using a globally name semaphore, it does not release the waiting process if the other process is killed / terminated. WaitForSingleObject() will wait until it times out (which may be INFINITE or hours).
How do I stop WaitForSingleObject() from waiting when the other process is killed or terminated?
In this case, there is a single count on the semaphore used to control read/write requests of a shared buffer. The Requester signals the Provider to provide certain data, the Provider updates the buffer and signals back to the Requester that it can now read the buffer.
I suggest that you switch to using WaitForMultipleObjects and wait for the handle of the process that might get terminated (or thread if you want to do this within a single process) in addition to your semaphore handle. That way you can continue to use INFINITE timeouts. Just have to check the return value to see which object was signalled.
Also, I would consider a process terminating while holding a semaphore somewhat of a bug, particularly a semaphore used for actual inter-process communication.
Adding to the accepted answer.
I added logic if the waitms was going to be longer than some value maxwaitms then the requester/provider exchange the providers process id (GetCurrentProcessId()) before the long process. The requester opens a handle (OpenHandle()) to the provider process and waits on both the semaphore and the process handle to know when writing is done (or process terminated).

waitpid in infitine wait state after PTRACE_ATTACH

I have integrated Google-Breakpad in my C++ application. Now, I am deliberately crashing the application but it hangs-up in my Ubuntu i686 system. I have to put printf everywhere in Breakpad to check where exactly it is hanging. So, in breakpad, a clone child process is being created and in that process ptrace(PTRACE_ATTACH, pid, NULL, NULL) followed by waitpid(pid, NULL, __WALL) syscall is being called on every thread. With one particular thread waitpid is entering in infinite wait state and I then have to deliberately kill the application.
Does anyone knows why exactly this is happening? Why with this one particular thread waitpid() is going in infinte wait state? Is there any solution for the same?
Thanks.
In general, PTRACE_ATTACH does not guarantee that a process will have anything to report. After PTRACE_ATTACH, waitpid will trigger only if one of two things happen:
The debugee receives a signal.
The debugee exists.
Some things are tantamount to one of those things. For example, if the debugee calls execve, then after a successful execution the kernel makes it appear as if the debugee received a TRAP signal.
If none of those situations happen, there is no reason for PTRACE_ATTACH to do anything at all.
If you want waitpid to return (say, because you want to change the debugee's state), then simply send a signal to the thread after calling PTRACE_ATTACH. This will guarantee that the thread have something to tell you.

How to catch console-closing event?

The context of my problem is:
I have a Windows .NET app (GUI) running as a main process.
From this (parent) process, I create a couple of sub-processes as console processes.
The main process sends data to the children processes through named pipes.
In the main app, I have a list of the sub-processes.
My probleme is that each console has a close ("x") button and can be terminated (whatever the way it is). Since I keep a list of the created consoles in my main app, I would like to know when a console is killed or exited.
My console (child process) program is simply a "main()" with a loop function that reads the pipe (and displays the data). It has no message system or whatever else that could handle a windowing "exit".
The first idea that comes to my head is to poll the sub-processes from the main app to refresh the list. But this means I have to introduce a timer or a thread that watches the consoles. I don't like the idea.
Does someone have a better idea?
WaitForSingleObject(hThread, 0) will tell you whether the thread specified in hThread argument is signaled and therefore finished. Same goes to hProcess.
Both handles of your child process are returned after CreateProcess() call. You can either close them immediately, or monitor using WaitForSingleObject.

Why can't terminate a process if its threads are in unkown states?

From my experience, when main thread is ready to exit, it should wait until other threads normally exit.
But from this link http://msdn.microsoft.com/en-us/library/ms686722(v=VS.85).aspx, it looks when process is terminated, all related resources are freed, so if certain worker thread is doing heavy work, waiting may be a litter longer. Can I ignore the waiting?
Also in the above link, I find
Do not terminate a process unless its
threads are in known states. If a
thread is waiting on a kernel object,
it will not be terminated until the
wait has completed. This can cause the
application to hang.
This is too short to understand why killing a thread in unknown states when process exits is wrong.
can someone give me more detail about the problem?
Thanks
So, when a thread is waiting on an object in the kernel, it will not exit until the waiting is over.
So, let's say you have an application with 3 threads, in the following states:
Main thread, currently idle
UI handling thread, currently idle
A thread waiting on a kernel object
If you kill the process, thread 2 will die, making the UI input handlers die, and therefore giving the appearance that the application is unresponsive (hung). Until thread #3 finishes waiting on the kernel, the main thread won't exit, and so the process remains running, and the process resources don't get released.
So, I think it's basically saying that it's better to ask a process to exit normally, instead of sending it a kill signal, because you can get yourself into a situation like the one described if any of the process threads are waiting on kernel objects.

how long it takes for kernel handles to close by Windows when an application crashes

I know Windows close kernel handles when an application crashes, but if I want to wait on this event, can I be sure it will happen in milisec or it might take a while? I would like to trigger a new function the moment one application is crashed and I'm checking if this handle is NULL but it seems like I can't get a NULL value in this case.
How long it will take may vary depending upon many factors including implementation, type of crash, etc. It might take awhile.
If you want to know when a process has crashed, you should set up a "watchdog" thread or process that waits on the application's Process Handle, using a function such as WaitForSingleObject. When the process dies, the event will be signaled and you can act accordingly.
Windows does not close handles when an application "crashes" - it closes them when the process terminates, no matter how the process terminates. By the time this happens the variables don't exist any more because the user mode address space has been shut down.
What are you trying to do?

Resources