Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to store back trace info to a file? #260

Open
Allen1218 opened this issue Apr 11, 2022 · 2 comments
Open

How to store back trace info to a file? #260

Allen1218 opened this issue Apr 11, 2022 · 2 comments
Labels

Comments

@Allen1218
Copy link

How to store back trace info to a file?

I want to store this segment fault info to a file, how to realize(or configuration) it ?
Thanks!

@oold
Copy link
Contributor

oold commented Apr 28, 2022

This is not a help forum, but here's a minimal example of how to do it for one signal.

#include <backward.hpp>

#include <csignal>
#include <cstdlib>
#include <fstream>

// This is definitely not async-signal-safe. Let's hope it doesn't crash or hang.
void handler(int signo) {
    if (std::ofstream file_stream("my_stacktrace.log", std::ios::trunc); file_stream.is_open()) {
        file_stream << "Caught signal " << signo << ".\nTrace:\n";
        backward::StackTrace st;
        st.load_here(32);
        backward::Printer p;
        p.print(st, file_stream);
    }

    // Raise signal again. Should usually terminate the program.
    std::raise(signo);
}

int main() {
    // Repeat this for each signal you want to catch and log.
    struct sigaction act {};
    // Allow signal handler to re-raise signal and reset to default handler after entering.
    act.sa_flags = SA_NODEFER | SA_RESETHAND;
    act.sa_handler = &handler;
    sigfillset(&act.sa_mask); 
    sigdelset(&act.sa_mask, SIGSEGV /* or other signal */);
    if (sigaction(SIGSEGV /* or other signal */, &act, nullptr) == -1)
        std::exit(EXIT_FAILURE);

    int* invalid_ptr = nullptr;
    *invalid_ptr = 0; // Cause SIGSEGV. Could also std::raise(SIGSEGV).
}

@bombela
Copy link
Owner

bombela commented Oct 11, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants