Throw stack trace from program kill

Steven Schveighoffer schveiguy at gmail.com
Sun Jan 16 18:22:04 UTC 2022


On 1/16/22 1:03 PM, Paul Backus wrote:
> 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.

Does this work normally? The memory error handler for Linux jumps 
through a lot of hoops to be able to throw an error from a signal 
handler. See 
https://github.com/dlang/druntime/blob/master/src/etc/linux/memoryerror.d

-Steve


More information about the Digitalmars-d-learn mailing list