If I'm right the OOM will send your process a SIGTERM signal, so you can handle it as you want.
I was not right, most probably OOM will send you SIGKILL and you can not do anything. But under certain circumstances you will get a SIGTERM before.
(non tested draft)
#include <csignal>
void signal_handler(int signal) {
// Your handling code here
}
int main() {
// Install handler (assign handler to signal)
std::signal(SIGINT, signal_handler);
}
C counterpart:
#include<signal.h>
#include<unistd.h>
void signal_handler(int signo)
{
if (signo == SIGTERM) {
// your handling code
}
}
int main(void)
{
if (signal(SIGTERM, signal_handler) == SIG_ERR) {
printf("\nError installing handler\n");
}
// Rest of your application
}
Be careful when handling signals, as you are overriding the default behavior. Your program should not ignore important signals like SIGTERM or SIGINT: the handling function has to do the work of finishing the program or maybe calling the original handler.
On the other hand, you can play with it: if you are sure the problem is the allocated memory you could try to free unused space and try to continue the work (but you need to ensure the signal reason was that).