I have a C program that goes like:
while(1){
if(flag1){
...
}
if(flag2){
...
}
}
Now these flags will be raised in handlers for SIGINT AND SIGTSTP signals. The terminal just shows ^C and ^Z when Ctrl+C or Ctrl+Z is entered, but the conditional code blocks are not executed.
However the exact same program, but if I give a printf like below:
while(1){
printf(" ");
if(flag1){
...
}
if(flag2){
...
}
}
The program responds to the Ctrl+Z or Ctrl+C signals, and the respective conditional code blocks are executed. Could someone explain this behavior? I am not sure why keeping the terminal busy with something being printed continuously, makes my program respond to the signals, while not otherwise.
The conditional code blocks could be optimized out, because compiler doesn't know these variables can change out of the loop. Define flags as volatile, i.e.
volatile int flag1;
...
This way compiler knows not to make any assumptions about the values of these variables.