Eddie
Eddie

Reputation: 51

Call a specific function when the console program terminates

I'm on windows and I want to call a specific function when the program terminates.

For example:

void close_program()
{
    /*do stuff*/
    printf("Goodbye.\n");
}

I tried atexit() but it only worked on casual and regular exits such as a call to the function exit() or when the main returns a value to the OS.

I found out that HandlerRoutine() seems like a solution as windows sends a CTRL_CLOSE_EVENT value signal to the process closed by the user (either just close button or end task through task manager). The problem is I tried a really basic piece of code and it said 'undefined reference to HandlerRoutine' and that it returned 1.

The piece of code:

#include <stdio.h>
#include <windows.h>

int main()
{
    while(1)
    {
         if(HandlerRoutine(CTRL_CLOSE_EVENT))
         {
              printf("Program is being terminated...\n");
         }
     }
     return 0;
}

I use MinGW.

Any idea what is the problem might be ?

According to MSDN there is no need for linkage.

Upvotes: 4

Views: 413

Answers (3)

Adriano Repetti
Adriano Repetti

Reputation: 67118

HandlerRoutine is the callback function that will be invoked when console will be terminated. It's not the function you have to call but the signature (defined as HANDLER_ROUTINE) of your function (that will be invoked by Windows itself):

BOOL WINAPI HandlerRoutine(DWORD dwCtrlType);

You'll inspect dwCtrlType to check for CTRL_CLOSE_EVENT returning (usually) TRUE. To attach your function and make it called you have to use SetConsoleCtrlHandler() API function, like this:

BOOL YourHandler(DWORD dwCtrlType)
{
    if (CTRL_CLOSE_EVENT == dwCtrlType)
    {
    }

    return TRUE;
}

Now you have your function but you instruct Windows to call it:

int main()
{
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)YourHandler, TRUE);

    // Do your stuff here

    return 0;
}

Please note that you can register more than one handler, they'll be called in chain up to the one that returns TRUE. For a complete example just consult MSDN.

Upvotes: 3

Neowizard
Neowizard

Reputation: 3017

From the MSDN page you linked

HandlerRoutine is a placeholder for the application-defined function name.

What you need to do is create a callback (of PHANDLER_ROUTINE type) and then use SetConsoleCtrlHandler to register this callback.

Upvotes: 0

iqstatic
iqstatic

Reputation: 2382

Try including wincon.h explicitly. I know there are a number of child header files that are automatically included with windows.h but many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies. wincon.h is one such child header file used for console services.

Upvotes: 0

Related Questions