How To Allow Atomics Use In C++ Signal Handlers
C++11 allows the use of atomics in signal handlers, and with the advent of C++ 17 the signal handler feature was again improved. The std::atomic_flag
is an atomic boolean type that is guaranteed to be lock-free and can be used in signal handlers. Moreover, the
header in C++ has an integer type std::sig_atomic_t
that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to use atomic_flag in C++.
How to allow atomics use in C++ signal handlers?
The
header in C++ (or signal.h
in C) has an an integer type std::sig_atomic_t
that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to allow atomics use in C++ signal handlers.
Here is how we can use it:
#include
volatile sig_atomic_t flag = 0;
|
Is there a full example of how to use atomics in C++ signal handlers?
Here is an example that has a signal handler and uses sig_atomic_t
flag from
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include #include
volatile sig_atomic_t flag = 0;
void handler(int signum) { flag = 1 ; }
bool signal_check() { if ( signal( SIGINT, handler) == SIG_ERR ) { return false; }
if (flag) std::cout << “Flag ON (signal received)n”; else std::cout << “Flag OFF (signal not received)n”;
return true; }
int main(void) { bool b; b = signal_check(); std::cout << “Signal Check:” << b << std::endl;
raise (SIGINT);
b = signal_check(); std::cout << “Signal Check:” << b << std::endl; system(“pause”);
return 0; }
|
The output will be as follows:
Flag OFF (signal not received) Signal Check:1 Flag ON (signal received) Signal Check:1 Press any key to continue . . .
|
For more information on this feature, see Allow atomics use in signal handlers Proposal document.
If you want to know more about signals and error handlers, I recommend you “CERT C Coding Standard, Second Edition, The: 98 Rules for Developing Safe, Reliable, and Secure Systems”.
https://www.informit.com/store/cert-c-coding-standard-second-edition-98-rules-for-9780321984043
C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise version.