Reputation: 11002
The following is a simplified example of my scenario (which is very common it seems);
#include <signal.h>
void doMath(int &x, int &y);
void signal_handler(int signal);
int main() {
signal (SIGINT,signal_handler);
int x = 10;
int y;
doMath(x,y);
while(1);
return 0;
}
void doMath(int &x, int &y) {
for(int y=0; y<=x; y++) {
cout << y << endl;
}
return;
}
void signalHandler(int signal){
doMath(x,y);
exit(1);
}
This basic program prints 1 to 10 on the screen and just hangs there until CTRL+C is pressed. At this point I want the doMath() function to run again. The only way I can see this happening is if I pass x and y to signalhandler() so it can then pass them onto doMath(), and a reference to the doMath() function also.
It my actual program there are two doMath() functions and many more variables, I would like a final dump of the variable values. So, it seems like an inefficient way passing all those variables to signalHandler to then be passed on to the two functions. Is there another way around this?
Upvotes: 0
Views: 163
Reputation: 64308
I think you'll need to use a global variable.
While global variables should be avoided in general, sometimes there is no other choice. Try to use as few as possible and document their use clearly:
#include <signal.h>
void signalHandler(int signal);
void doMath(int &x, int &y);
struct DoMathArgs {
int x;
int y;
void callDoMath() { doMath(x,y); }
};
// We have to use this global variable to pass the arguments to doMath when
// the signal is caught, since the signal handler isn't passed any arguments
// that we can use for our own data.
DoMathArgs global_do_math_args;
int main() {
signal (SIGINT,signalHandler);
global_do_math_args.x = 10;
global_do_math_args.callDoMath();
doSomethingForever();
return 0;
}
void signalHandler(int signal) {
global_do_math_args.callDoMath();
exit(1);
}
void doMath(int &x, int &y) {
for(int y=0; y<=x; y++) {
cout << y << endl;
}
return;
}
Upvotes: 2
Reputation: 31579
A much more efficient approach would to define an event, wait on it in main, set it off in the signal, and after waiting call doMath in main again.
Upvotes: 0