With the following code:
#include <stdio.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
long long int cpt=0,nb=3;
bool out=false;
void alarm_handler() {out=true;}
void prime()
{
while (nb++) {
for (long long int j=2;j<nb;j++) {
if ((nb % j)==0) {cpt++;break;}
}
if (out) return;
}
}
int main()
{
struct itimerval timer;
bzero(&timer,sizeof(timer));
timer.it_value.tv_sec=1;
signal(SIGALRM,alarm_handler);
int res=setitimer(ITIMER_REAL,&timer,NULL);
if (res<0) perror("error setting signal original timer");
else prime();
printf("cpt=%Ld nb=%Ld\n",cpt,nb);
fflush(stdout);
exit(0);
}
The program behaves correctly when compiled with gcc or clang without optimizations. However, as soon as -O is used, it never ends, as if the value of the out
variable was never read inside the prime()
function (I am sure the variable is properly set, as it is possible to add a print in the handler, and it is set).
Is it possible to force the compiler to keep on checking the value of out
in prime()
?