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

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?

Related

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.
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, ...).

Is it possible to advance a deadlocked thread? stuck at WaitForSingleObject

If I have an app that is creating threads which do their work and then exit, and one or more threads get themselves into a deadlock (possibly through no fault of my own!), is there a way of programmatically forcing one of the threads to advance past the WaitForSingleObject it might be stuck at, and thus resolving the deadlock?
I don't necessarily want to terminate the thread, I just want to have it move on (and thus allow the threads to exit "gracefully".
(yes, I know this sounds like a duplicate of my earlier question Delphi 2006 - What's the best way to gracefully kill a thread and still have the OnTerminate handler fire?, but the situation is slightly different - what I'm asking here is whether it is possible to make a WaitForSingleObject (Handle, INFINTE) behave like a WaitForSingleObject (Handle, ItCantPossiblyBeWorkingProperlyAfterThisLong)).
Please be gentle with me.
* MORE INFO *
The problem is not necessarily in code I have the source to. The actual situation is a serial COM port library (AsyncFree) that is thread based. When the port is USB-based, the library seems to have a deadlock between two of the threads it creates on closing the port. I've already discussed this at length in this forum. I did recode one of the WaitForSingleObject calls to not be infinite, and that cured that deadlock, but then another one appeared later in the thread shutdown sequence, this time in the Delphi TThread.Destroy routine.
So my rationale for this is simple: when my threads deadlock, I fix the code if I can. If I can't, or one appears that I don't know about, I just want the thread to finish. I doesn't have to be pretty. I can't afford to have my app choke.
You can make a handle used in WaitForSingleObject invalid by closing it (from some other thread). In this case WaitForSingleObject should return WAIT_FAILED and your thread will be 'moved on'
If you don't use INFINITE but just set a given timeout time, you can check if the call returned because the time out time expired or because the handle you were waiting for got into the signalled state. Then your code can decide what to do next. Enter another waiting cycle, or simply exit anyway maybe showing somewhere 'hey, I was waiting but it was too long and I terminated anyway).
Another options is to use WaitForMultipleObjects and use something alike an event to have the wait terminate if needed. The advantage it doesn't need the timeout to expire.
Of course one the thread is awaken it must be able to handle the "exceptional" condition of continuing even if the "main" handle it was waiting for didn't return in time.

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.

What could cause a C++Builder / Delphi thread and application to not shut down?

Once, during testing, my C++Builder / Delphi application raised an uncaught exception in a background worker thread. EurekaLog caught the exception and sent an error report, as I expected, and everything appeared to be okay.
However, when I closed the application's main window, something remained running in the background, because the application was still listed in the task manager (and still had resources open).
I've tried to duplicate this problem, by deliberately introducing various bugs in the background worker thread, but I can't.
What could cause a thread and application to remain running like this, even after the main window has closed (and, presumably, PostQuitMessage has been called)?
How can I ensure that the application always cleanly shuts down?
The first rule is that threads main executor methods should be written so that they can be signalled and shut down properly, and the second rule is that you shouldn't just shut down your app's main thread first, and then hope that the other threads shut down in their own time, to be safe, you should signal all the background threads to stop, wait for that shutdown to complete, and THEN shutdown your main thread. A minimal THREAD example:
procedure TMyThread.Execute;
begin
Init;
while not Terminated do
OneWorkItem; // inside OneWorkItem, you ALSO need to check for Terminated
end;
A minimal main form/main-thread example:
procedure TMyMainForm.CheckAndShutdown;
begin
if FPendingShutdownFlag then
if AllBackgroundThreadsTerminated then
Self.Close;
end;
You could set FPendingShutdownFlag and have the function above called from the application idle processing loop. When you have the user click the main form FormClose, if AllBackgroundThreadsTerminated returns false, set CanClose to false, and set the FPendingShutdownFlag := true instead.
If you make an endless loop (while true), the application does not shut down cleanly, even if it looks like that to you. Somehow, the application is terminated, and the running threads may just suddenly go away quietly, or they may deadlock or otherwise fail on you, as they may be using resources in thread 2 that you are busy freeing in thread 1.
You may have one or more intentional race conditions because you might not have written your thread execute method to be interruptable, or you may start the closing of the main application thread and the VCL and its objects, before you are sure that your background threads are completely shut down.
Are you sure that worker thread terminated, and main thread is not waiting for it to finish?

Attach gdb to process before I know the process id

I am debugging a process on a web server running Linux. The process is invoked once a request is coming from a web-page. In order to debug the process, I look at the running processes list (using top), I spot the relevant process (named apache2) by it's CPU usage (quite easy, since it is usually on top of the list), and I attach the gdb session to the process id. Of course I can call the attach PID command only after the process is up.
The only problem is that this process-id-spotting takes a second or two, so I cannot stop at functions which are called during the first second or two. (The whole process takes about a minute so in most cases it is not a problem).
Is there any way of doing this automatically, so I can save these couple of seconds and start the attachment earlier?
You can attach to the parent process and catch forks. Don't forget to set follow-fork-mode child.

Resources