I am trying to implement a handler that on SIGSEGV will collect some information such as process-id, thread-id and a backtrace and write this information to a file/pipe/socket.
The problem lies in that there is the (probably pretty high) possibility that if one thread experienced a SIGSEGV that the others will shortly follow. If two threads happen to make it to the bit of code where they’re writing their report out at the same time then they’ll interleave their writing (to the same file).
I know that I should only be using async-signal-safe functions as detailed in signal(7)
I also have seen at least two cases here and video linked in top answer here where others have used pthread_spin_trylock to get around this problem.
Is this a safe way to prevent the above problem?
On most systems
pthread_spin_trylockwill be implemented with an atomic compare-and-swap (CAS instruction which is interrupt-safe at least on x86 (can’t speak for others).I would probably use the CAS myself to make sure that’s what happens.
Here is the gcc doc for it:
http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html
And example code:
in your signal handler: