0

I encounter multiple times where Linux Out of Memory Killer watchdog on Linux is killing my application, this is hard to debug and identify...

Is there anyway in a c/c++ application running under Linux to print a message before the application is killed?

JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
  • Not really, but you can attach a debugger... `sudo gdb -ex run --args ./program arg1 arg2 ...` – Siguza Apr 05 '16 at 20:11
  • How is it killed? Immediate SIGKILL? Than I am afraid there is nothing you can do, rather than modify your app to not eat that much memory. – SergeyA Apr 05 '16 at 20:23
  • Any such functionality would defeat the purpose of the OOM killer - it would be a way to avoid its action. – Martin James Apr 05 '16 at 20:48

1 Answers1

2

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).

Xiromoreira
  • 103
  • 1
  • 7