Handling a process termination.
-
Yes there is, its called
WM_QUIT
. A Win32 Message. You must create a Win32 app for this code. This app is not a console app , its a windows app and will useint WinMain()
instead ofint main().
PeekMessage()
looks into the message queue and checks to see if any messages are waiting. If not, the program will continue on. If our message isWM_QUIT
, then that means its time to exit and return to Windows.// example code snippet #include <windows.h> LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_QUIT: // Normal exit // put stuff to do before exiting here break; case WM_CLOSE: // Abnormal termination // put stuff to do before exiting here // this only works if you terminate the window from Taskmanager's "end task" MessageBox(NULL, "user terminated the window from Taskmanager!", "abnormal exit" , MB_OK); DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; //Step 1: Registering the Window Class wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } // Step 2: Creating the Window hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(
That will only work if the app has a message loop, and is still pumping messages
-
I seem to remember that SIGTERM is never raised, so you want check SIGABRT. I'm sure you'll find that in the doc.
-
This will work only in normal program termination. But if for example application is freezed and user wants to shut it with Task Manager - the execution will not run to main loop, cause application is freezed and dont getting messages from queue. Therefore I need some OS-level way to catch abnormal termination.
Ok, try TerminateProcess(). Check out these links. How to kill a process given a name[^] How To Terminate an Application "Cleanly" in Win32 http://support.microsoft.com/default.aspx?scid=KB;en-us;q178893[^] http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/a3b5a913-e7f9-454e-9913-658219c5124b[^]
-
Ok, try TerminateProcess(). Check out these links. How to kill a process given a name[^] How To Terminate an Application "Cleanly" in Win32 http://support.microsoft.com/default.aspx?scid=KB;en-us;q178893[^] http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/a3b5a913-e7f9-454e-9913-658219c5124b[^]
-
Ok, try TerminateProcess(). Check out these links. How to kill a process given a name[^] How To Terminate an Application "Cleanly" in Win32 http://support.microsoft.com/default.aspx?scid=KB;en-us;q178893[^] http://social.msdn.microsoft.com/Forums/en-US/vssmartdevicesnative/thread/a3b5a913-e7f9-454e-9913-658219c5124b[^]
The OP Doesn't want to terminate a process, he wants to INTERCEPT process termination in order to do cleanup. Please stop confusing the issue.
-
Well, the questions was not "How terminate process?", but "How to execute some code when process terminated normal or abnormal?" :).
How to execute some code when process terminated normal or abnormal? Answer: WinAPI (Win32) specific only. If you close the window from Taskmanager's "End Task", then you get the
WM_CLOSE
notification. TheWM_CLOSE
message is sent as a signal that a window or an application should terminate. BUT If you click on "End Process" from task manager, then there's no way to handle it, in .NET or Win32. You better hope that the end user clicks on Taskmanager's "End Task" and not on "End Process" .LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_CLOSE: // !!!!!!!!!!! Insert code here. // this only works if you close the window from Taskmanager's "End Task" MessageBox(NULL, "closed the window from Taskmanager!", "abnormal exit" , MB_OK); break; default: return DefWindowProc(hWnd, message, wParam, lParam); }
modified on Friday, April 30, 2010 11:01 AM
-
How to execute some code when process terminated normal or abnormal? Answer: WinAPI (Win32) specific only. If you close the window from Taskmanager's "End Task", then you get the
WM_CLOSE
notification. TheWM_CLOSE
message is sent as a signal that a window or an application should terminate. BUT If you click on "End Process" from task manager, then there's no way to handle it, in .NET or Win32. You better hope that the end user clicks on Taskmanager's "End Task" and not on "End Process" .LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_CLOSE: // !!!!!!!!!!! Insert code here. // this only works if you close the window from Taskmanager's "End Task" MessageBox(NULL, "closed the window from Taskmanager!", "abnormal exit" , MB_OK); break; default: return DefWindowProc(hWnd, message, wParam, lParam); }
modified on Friday, April 30, 2010 11:01 AM
Hey, I know how to execute some code when application closing in normal case. I'm not novice, and know how Windows messages system is working. The question is more advanced. What if for example, something go wrong, application freezing - and user terminates it using task manager, terminates it dirty? I need to do some code here. Probably this is impossible, but look at the answer Michael Godfroid gave me above. This seems to be what I look for. So I'm going to investigate this.
-
Hey, I know how to execute some code when application closing in normal case. I'm not novice, and know how Windows messages system is working. The question is more advanced. What if for example, something go wrong, application freezing - and user terminates it using task manager, terminates it dirty? I need to do some code here. Probably this is impossible, but look at the answer Michael Godfroid gave me above. This seems to be what I look for. So I'm going to investigate this.
-
Tried it. Doesn't seem to work. I made a console app added a line to pause execution then terminated it from the task manager. I didn't get the message. :(
Did you tried this in debugger? I guess with debugging it will not work. Try to make infinite loop instead. I mean try following: In main() make infinite loop. In signal handler need to do something to identify we here, probably type to console (but this might not work). Run application without debugging. It's important, cause things like this might behave different when debugger attached. I didnt tried it myself yet, going to check this on monday.
-
Tried it. Doesn't seem to work. I made a console app added a line to pause execution then terminated it from the task manager. I didn't get the message. :(
Btw, here is from doc. Note SIGINT is not supported for any Win32 application. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application such as one in UNIX to become multithreaded, resulting in unexpected behavior. So terminating from Ctrl+C will not work. Try to kill process from task manager.
-
Tried it. Doesn't seem to work. I made a console app added a line to pause execution then terminated it from the task manager. I didn't get the message. :(
For console:
CTRL_CLOSE_EVENT
or the Console process termination message. If you close the console from Taskmanager's "End Task", then you get theCTRL_CLOSE_EVENT
notification. TheCTRL_CLOSE_EVENT
message is sent as a signal that a console application should terminate. BUT If you click on "End Process" from task manager, then there's no way to handle it, in .NET or Win32. The code below displays the message "Signal to quit was received" once you click on "End Task" from task manager.modified on Friday, April 30, 2010 12:01 PM
-
Btw, here is from doc. Note SIGINT is not supported for any Win32 application. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application such as one in UNIX to become multithreaded, resulting in unexpected behavior. So terminating from Ctrl+C will not work. Try to kill process from task manager.
I used this code in release mode and killed it from the task manager, while running it from the command line so as to catch the text. - It never came. Not quite sure what SIGINT has to do with the price of chewing-gum in Czechoslovakia? ;P We're not trying to interrupt the process, we're just terminating it.
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>void SignalHandler(int signal)
{
printf("Application aborting...\n");
}int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;previousHandler = signal(SIGABRT, SignalHandler); getch(); abort();
}
However, now that I can't find the page that I lifted the above code from I can't help but get the feeling that this particular approach is an exercise that won't succeed. I reckon that the signal is only thrown when the _application_ calls abort(), and not when windows calls abort(theApp). I wonder if you'd have to hook TerminateProcess or something similar. I've a feeling that such a solution will require a fairly hard-core answer. Good-luck:thumbsup:
-
Hi all! C++, WinAPI Is there any way to catch when process is being terminated (i.e. terminated by user from Task Manager, or ended in normal case) and do some code there. In other words I need to execute some code, in any cases when program is ending execution. Thanks
When Task Manager uses
TerminateProcess()
to end a process, there is no notification. Also, there are no notifications generated forWH_CBT
hook procedures."One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"Man who follows car will be exhausted." - Confucius
-
Hi all! C++, WinAPI Is there any way to catch when process is being terminated (i.e. terminated by user from Task Manager, or ended in normal case) and do some code there. In other words I need to execute some code, in any cases when program is ending execution. Thanks
Can't really be done folks. Task manager sends a WM_CLOSE or CTRL_CLOSE_EVENT first, but only if you terminate from the applications tab. You'll be able to intercept that one with the SetConsoleCtrlHandler function. Otherwise task manager will fire a TerminateProcess, which cannot be intercepted ever. Read it from the master himself here.[^]
-
Hi all! C++, WinAPI Is there any way to catch when process is being terminated (i.e. terminated by user from Task Manager, or ended in normal case) and do some code there. In other words I need to execute some code, in any cases when program is ending execution. Thanks
Hi, The task manager uses two methods of terminating a process depending on which tab has been selected. The tab labled 'Applications' will send a WM_CLOSE message to the window when 'End Task' has been selected which can easily be intercepted and handled. The task manager tab labled 'Processes' utilizes TerminateProcess[^] which cannot be intercepted/blocked by the target process. Some useful documentation from Microsoft Windows Internals Fourth Edition[^]: Processes, Threads, and Jobs[^] Best Wishes, -David Delaune
-
Hi all! C++, WinAPI Is there any way to catch when process is being terminated (i.e. terminated by user from Task Manager, or ended in normal case) and do some code there. In other words I need to execute some code, in any cases when program is ending execution. Thanks
-
Hi all! C++, WinAPI Is there any way to catch when process is being terminated (i.e. terminated by user from Task Manager, or ended in normal case) and do some code there. In other words I need to execute some code, in any cases when program is ending execution. Thanks
You could try and hook the
TerminateProcess
API. But API hooking is not at all possible/recommended these days.«_Superman_» I love work. It gives me something to do between weekends.
Microsoft MVP (Visual C++)