Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate worker thread properly in an injected DLL?

I'm injecting a DLL into some process, the DLL has a worker thread that is running a message loop.

I'd like to quit the thread properly i.e. post a quit message (PostThreadMessage) and wait for it (WaitForSingleObject).

Where can i wait for this thread to close? I can't do it on DLL_PROCESS_DETACH because by then all of the threads are closed or terminated and I don't know when the process is about to close.

My only thought was, Is there a way to intercept the main thread message loop and look for the WM_CLOSE\DESTROY msgs?

I'd love to hear any other ideas\solutions.

Edit:
Tried to hook the main thread using SetWindowsHookEx with WH_CALLWNDPROC but it didn't worked quite well, I managed to hook and receive the thread's messages. However, I didn't received WM_QUIT message only WM_DESTROY and WM_NCDESTROY and they are all were associated with windows.

Thanks,
Omer

like image 550
Omer Avatar asked Jun 23 '11 11:06

Omer


2 Answers

The process has no clue that the thread exists, it is not going to care whether it exits nicely. In fact, it will terminate it if the program was written in, say, C, its runtime library calls TerminateProcess when its main() method exits. Harikiri style.

If you externally care about the thread, say in a program that you wrote that is monitoring the thread, then you need to leave a breadcrumb when it exits. Either by communicating that to your program with whatever process interop mechanism you use, like a named pipe. Or by setting a named event. Do make sure you deal with the harikiri scenario, you'll want to also check if the process handle gets signaled to indicate that it terminated.

like image 170
Hans Passant Avatar answered Oct 19 '22 07:10

Hans Passant


If you need to perform some action on "About-To-Close" you need to hook the main thread using SetWindowsHookEx with WH_CALLWNDPROC and look for WM_CLOSE and take action/signal the thread to close.

like image 38
cprogrammer Avatar answered Oct 19 '22 08:10

cprogrammer