0

I'm new to C, and I'm reading a book which says:

In one common handler design, the handler records the receipt of the signal by writing to a global flag. The main program periodically reads the flag, responds to the signal, and clears the flag. For flags that are shared in this way, C provides an integer data type, sig_atomic_t, for which reads and writes are guaranteed to be atomic (uninterruptible) because they can be implemented with a single instruction: volatile sig_atomic_t flag; Since they can’t be interrupted, you can safely read from and write to sig_atomic_t variables without temporarily blocking signals

I'm still a little bit confused, below is my questions:

I checked the source code and found that sig_atomic_t is actually int, so why not we just use int as volatile int flag;? do we use sig_atomic_t just for emphasis?

amjad
  • 3,048
  • 1
  • 11
  • 42
  • 1
    It doesn't *have* to be an int, it can be a different type depending on CPU and OS. Use the typedef and you know it's an appropriate type for whatever system is being used. – Shawn Sep 14 '20 at 08:42
  • 1
    `sig_atomic_t` variables are guaranteed to have atomic semantics. `int` does not. Exactly how this is implemented is left for the compiler and standard C library to handle. – Some programmer dude Sep 14 '20 at 08:46
  • Does this answer your question? [How does sig\_atomic\_t actually work?](https://stackoverflow.com/questions/24931456/how-does-sig-atomic-t-actually-work) – Shawn Sep 14 '20 at 08:48
  • Also, `volatile` doesn't mean that the variable gets atomic access. – Lundin Sep 14 '20 at 08:48
  • 1
    Also see https://stackoverflow.com/questions/9606725/linux-why-is-sig-atomic-t-typedefed-to-int – Shawn Sep 14 '20 at 08:50

0 Answers0