mardi 28 décembre 2021

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.

Aucun commentaire:

Enregistrer un commentaire