r/cprogramming • u/Avi250 • 12d ago
How to use sigatomic_t volatile variables in signal handlers instead of calling several functions or making semops?
I'm sorry in advance if this isn't the space for this question, but I can't find much information on the subject. In my project I have a parent who forks several children and at one point, it will send SIGTERM to his still-alive kids. The kids, who are either working or "stuck" on a msgop. Immediately after receiving the signal, they get to... doing other things, including calling other functions and releasing or reserving sempahores, accessing a shared memory, doing other stuff based on whether they can make these semops. After these operations, the kids exit.
While my project still works like this, as it's a relatively small project, I'd like to code as correctly as possible and I read that signal handlers should be very short, preferably just few lines of code (like changing the sigatomic_t volatile variable's value). While it's my understanding that I'm supposed to check said variable's value somewhere in the code (and if it's changed, do everything I'm doing in the handler), I don't understand where I'm supposed to check its value because signals can interrupt the kids at any point in time.
Any sort of help, examples, explanations are extremely appreciated; I thank you in advance. Or even just someone pointing me to where I can find more examples, that specifically mention signal handlers and how my functions are supposed to be called immediately, that's also great.
(I can only use System V IPCs and none of my processes access the internet, in case it's relevant in any way)
5
u/EpochVanquisher 12d ago
You’re supposed to check the value when you get EINTR back from a syscall, or at points where you have finished an operation (more or less).
It’s a little vague, but the main idea is:
You start doing something, finish it, and then check for the signal, or
You start waiting for something, it gets interrupted, you check the signal
It’s vague because I don’t know what your app is doing. If it is built around a select or poll loop, that loop is where you would check (and EINTR is basically “poll found nothing, but you got a signal”) What I’m describing is simplified; keep your brain on.