Q:

Platform independent way to catch console/terminal close event

My question simply is:

Is it possible to catch and process console/terminal closing event platform independently?

My question isn't the same as this question, or this, or this. None of the answers on these questions provide a platform independent way. So, is there any way? If yes, then what is it? Or is it flat impossible? If so, why is that? I mean, why is it not possible to develop a library that could handle this?
EDIT: As @Yakk asked, I need it to work on both Windows and Linux, with the least code repetition possible. If it helps, I'm learning basic networking. I've built a simple chat app, in which I need to add entries in a chat history file while closing the app. I've implemented a way to close it from inside the app. But, as users are more likely to click the close button, I need to be able that event to do the operations. 

A:

There is no standard way to do so, and I am not aware of a library available, but it is not that hard to write it yourself:
#if defined(_WIN32) || defined(WIN32)
static void (*theHandler)(int);
static BOOL WINAPI winHandler(DWORD ctrlType)
{
    theHandler((int)ctrlType);
    return TRUE;
}
#endif

void installConsoleHandler(void (*handler)(int))
{
#if defined(_WIN32) || defined(WIN32)
    theHandler = handler;
    SetConsoleCtrlHandler(&winHandler, TRUE);
#else
    /* sigaction, as you find in your links */
#endif
}

If you keep this code, you might extend it later for other platforms:
#if windows
#elif linux || compatible
#elif whatever
#else
#error "not implemented for current platform"
#endif

and you get a real library...
The code above is usable in C and C++ (for this I preferred static over an anonymous namespace...), so you can place it in a .c file (and compile it as C). To make it work in C++ again (as you requested), you need to tell the C++ compiler that it is a C function (meaning that there is no name mangling as in C++, which would otherwise be applied and thus the function not found during linkage), so the header would contain:
#ifdef __cplusplus
extern "C"
{
#endif
    void installConsoleHandler(void (*handler)(int));
#ifdef __cplusplus
}
#endif

(Sure, you did not ask for C, but if you can get it almost for free (except for the extern "C" stuff), why not take it along? One never knows...)

