3

LinuxデーモンをC++で作成しました。コードは次のようなものです。

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
}

問題は、私のプログラムロジックが時々例外をスローすることです。どこで問題が発生したかを知るために、例外をキャッチするにはどうすればよいですか?

プレーンなコンソールアプリケーションの場合、キャッチされなかった例外がコンソールにダンプされることを私は知っています。私の場合、daemon(1、0)を呼び出した後、コンソールにアクセスできなくなりました。

Windowsでは、キャッチされなかった例外はOSによって保存され、コンピューター管理のイベントビューアーを介して表示できます。Linuxにも同様のメカニズムがありますか?

4

2 に答える 2

5

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.

于 2012-11-04T14:03:02.800 に答える
4

didiercが示唆するようにロギングを理解していると仮定すると、未処理の例外からのスタックトレースをstd::set_terminate()確認できるように、ハンドラーをインストールすることを検討できます。

#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();
}
于 2012-11-04T14:14:50.413 に答える