'Accessing variables of main() function inside signal handler in C++

I want to change the variables declared in the main function using signal handler when an user defined signal is sent to the process. I do not want to use any global variables.

Below is a sample code.

#include <iostream>
#include <csignal>

void signal_handler(int sig) {
    // I want to change value of b here
}

int main() {
    signal(SIGUSR1, signal_handler);
    int a, b = 10;
    while(1) {
        std::cin >> a;
        std::cout << a * b << std::endl;
    }
}

In place of 'b', it could be any other type of variable (a socket file descriptor, a mysql connection etc) which the program has to refresh once a signal is sent. Using global variables for all these tasks is not good.

So, please suggest the different methods for achieving it. Thank you.



Solution 1:[1]

You can declare it as a global variable, then you will be able to change its value from inside the function, because there is no other way to access a variable (beside the defined ones by signals functions) from a signal handler function due to its unique prototype. I found this answer that can clarify your doubts about using global variables when working with signals -> Providing/passing argument to signal handler . i hope that helps !

Solution 2:[2]

If it makes you feel any better, instead of using a global variable, you can use a private static member of a type specifically designed to handle your signal:

class SigHnd {
  private:
    static int b;
  public:
    static void signal_handler(int) {
      b = 20; 
    }   
    static int get_b() {
      return b;
    }   
};
int SigHnd::b = 10; 

You can access the value of b in your loop:

std::cout << a * SigHnd::get_b() << std::endl;

but nobody except the signal handler can alter it. And you can have it in any namespace you like to avoid it cluttering the root namespace.

You register it like you would have registered the free function handler:

signal(SIGUSR1, SigHnd::signal_handler);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 bitmask