简体   繁体   中英

Does Linux log an uncaught exception thrown by a daemon?

I have written a Linux daemon in C++. The code is something like this:

int main(int argc, char** argv)
{
    daemon(1, 0); // Daemonize itself, retaining the current working directory and redirecting stdin, stdout and stderr to /dev/null.
    // My program logic goes here
}

The problem is, my program logic throws exceptions occasionally. How do I catch the exceptions so that I can know where goes wrong?

I know that for a plain console application, the uncaught exception will be dumped to the console. In my case, after calling daemon(1, 0), the console is no longer accessible.

On Windows, any uncaught exceptions will be saved by the OS, and can be viewed via the Event Viewer in Computer Management. Is there a similar mechanism on Linux?

You have two solutions:

  • one: you change your call to the daemon function to

     daemon(1,1); 

    which will let the program still have access to stdout and subsequently the default behaviour of dumping uncaught exceptions to the console will be preserved.

  • two: you don't change the call, but you add a global try { /* main code here */ } catch(...){ /* logging code here */ } to log any uncaught exception to file.

Assuming you figure out your logging as didierc suggests, You might consider installing a std::set_terminate() handler so you can see the stack trace from the unhandled exception

#include <iostream>
#include <stdexcept>

#include <execinfo.h>

void
handler()
{
    void *trace_elems[20];
    int trace_elem_count(backtrace( trace_elems, 20 ));
    char **stack_syms(backtrace_symbols( trace_elems, trace_elem_count ));
    for ( int i = 0 ; i < trace_elem_count ; ++i )
    {
        std::cout << stack_syms[i] << "\n";
    }
    free( stack_syms );

    exit(1);
}   

int foo()
{
    throw std::runtime_error( );
}

int
main()
{
    std::set_terminate( handler );
    foo();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM