On Sunday, 16 January 2022 at 15:15:07 UTC, Hipreme wrote:
Is there some way to throw a stack trace when killing the program from the CTRL+C from the terminal?

It would help a lot into debugging occasional infinity loops

On POSIX, you can use the `sigaction` function to install a signal handler for `SIGINT`, the signal generated by CTRL+C. To terminate the program with a stack trace, simply have the signal handler `throw` an `Error`.

Here's an example program that demonstrates the technique:

```d
import core.sys.posix.signal;

extern(C) void handleCtrlC(int)
{
        throw new Error("Killed by CTRL+C");
}

void main()
{
        sigaction_t act = { sa_handler: &handleCtrlC };
        int errcode = sigaction(SIGINT, &act, null);

        f(); // call some functions
}

void f() { g(); }

void g() { h(); }

void h()
{
        while (1) {} // wait for ctrl+c
}

```

Make sure to compile with the `-g` option if you want your stack trace to have filenames and line numbers.

Reply via email to