Question Details

No question body available.

Tags

c++ multithreading stack-trace c++23

Answers (1)

Accepted Answer Available
Accepted Answer
December 23, 2025 Score: 9 Rep: 27,259 Quality: Expert Completeness: 80%

One problem is that the state of the stream in the C++ runtime library could be inconsistent at the time the signal handler is executed. Therefore, you should not be calling any stream I/O functions from the C++ standard library in the signal handler, as this may cause the program to crash.

However, depending on which platform you are using, it is likely possible to print output from the signal handler in a safe way.

For example, on Linux, it is safe to call functions that are explicitly listed as async-signal-safe. The system call write (which bypasses the C++ stream) is a function that is listed as async-signal-safe, so it allows you to print output safely from a signal handler.

Another problem is that std::stacktrace uses the default memory allocator, which could also be in an inconsistent state when the signal handler is executed. Therefore, using it from the signal handler may result in a crash.

However, it is possible to create a std::basicstacktrace object which uses your own memory allocator instead of the default memory allocator. If this allocator of yours is only used by the signal handler, and the signal handler is guaranteed to not be called again before the first call has finished executing (see reentrancy), then it should be safe to use this memory allocator, as long as this memory allocator does not call any functions that are not async-signal-safe.

This means that on Linux, your memory allocator cannot call mmap from inside the signal handler, because that function is not listed as async-signal-safe. However, your allocator is allowed to for example allocate memory from a memory buffer that was previously allocated using the default memory allocator outside the signal handler.

But doing all of this is rather complicated. Therefore, in the case described in the question, the easiest thing to do would probably be to create a core dump of the process, and to generate a stack trace from that core dump.


Whether you can rely on Linux system calls such as mmap to be async-signal-safe despite them not being explicitly listed as async-signal-safe is disputed.