Answer: Let’s first understand what an atomic operation is? An atomic operation is one that CPU executes in single unit! For ex. consider, if a machine were 16-bit, it would take one unit to execute an integer which is 16-bit and would take two units to execute a 32-bit integer. As we know that signal handler sets one of the variables of type ‘volatile sig_atomic_t’ to be truly safely handle a signal for which it’s installed and returns. Then, rest of the program examines periodically it’s value to ensure if that signal occurred. Restricted the signal handler to access atomic operations avoids the possibility of inconsistent results when another signal occurs in the middle of steps that access a non-atomic variable.
Since signals can’t be coordinated in time that is they can occur any time. Therefore, values which are modified by signal handler may change at any time. Because of this we can’t count on these variables having same value from one program statement to next. ‘Volatile’ keyword informs compiler of this fact, which prevents it from optimizing program so that meaning of such variable may change. Let’s consider an example below
if (atom_var) printf("TRUE"); else printf("FALSE"); if (atom_var) printf("TRUE"); else printf("FALSE");
Notice that what happens when above code fragment is executed, ordinary second test would result in same value as the first . Second test would result differently than first if signal handler modifies its value. Unless ‘atom_var’ isn’t declared to be volatile compiler might optimize the above code as below
if (atom_var) { printf("TRUE"); printf("TRUE"); } else (atom_var) { printf("FALSE"); printf("FALSE"); }
which results same as the previous code. Remember to declare variable that the signal handler is all to set to be of type “volatile sig_atomic_t”.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Buy C Books
- Apply for Computer Science Internship
- Buy Computer Science Books