3

I understand that accessing static variables in signal handlers is undefined behaviour, unless the variable is declared as volatile sig_atomic_t. I am, however, writing a program for a 64-bit machine, where sig_atomic_t happens to be 32-bit. Is there an long equivalent of sig_atomic_t which I can use?

I know that sig_atomic_t is merely a typedef of int, so maybe a volatile long will do; I'm just not comfortable with doing anything that is specifically undefined behaviour.

Thanks!

Einheri
  • 957
  • 1
  • 9
  • 22

2 Answers2

1

The answer appears to be "no", there is no long analog which is covered by the standard. The answer for Linux: Why is sig_atomic_t typedef'ed to int? goes into a lot of detail, and the quoted standards pointedly omit any types which could be larger than an integer.

As noted in Using long data inside signal handler., a signal handler can of course access data of any type, but cannot rely upon sharing data of other types.

Community
  • 1
  • 1
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • I suppose I've misunderstood the reason why some functions aren't safe in signal handler context, why sig_atomic_t is a typedef of int, etc. I gave it some thought and it makes sense now. – Einheri Apr 03 '15 at 16:39
0

The new C11 standard specified an optional concurrency model and a couple of types, which are safe for use in signal handlers.

Regarding signal handlers, it now says (emphasis mine):

the behavior is undefined if the signal handler refers to any object with static or thread storage duration that is not a lock-free atomic object other than by assigning a value to an object declared as volatile sig_atomic_t

A Lock-free type is one which the underlying architecture directly supports doing atomic operations on (locks need not be used).

So, #if __STDC_NO_ATOMICS__!=1 and <stdatomic.h> #defines ATOMIC_LONG_LOCK_FREE, you are guaranteed well-defined behaviour using atomic_long from <stdatomic.h> in place of volatile sig_atomic_t. This is e.g. the case with GCC 4.9+ on AMD64.

a3f
  • 8,517
  • 1
  • 41
  • 46