1

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?

Community
  • 1
  • 1
Thomas Mouton
  • 473
  • 4
  • 7
  • I think it would be better, if you deleted either the `c++` or the `c` tag and if you added the `race-condition` tag. This way people might better know in which language they can give you examples. And people who know something about race-conditions might get interested in the question. – Martin Thoma Aug 25 '12 at 07:55
  • Thank you. I've done as you suggested in hopes of attracting the right people to answer my question. – Thomas Mouton Aug 29 '12 at 21:37
  • What information are you going to write out that the core dump wouldn't have told you? – Joseph Garvin Sep 01 '12 at 00:47
  • The idea is to collect this from clients/users automatically, no coredump from them. – Thomas Mouton Sep 04 '12 at 14:14

1 Answers1

1

On most systems pthread_spin_trylock will 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:

 static int lock = 0; // global scope

in your signal handler:

 if (__sync_bool_compare_and_swap(&lock, 0, 1)) {
     // Got the lock
 } else
     pthread_exit(); // terminate this thread
Sergey L.
  • 21,822
  • 5
  • 49
  • 75