I am trying to understand the following example of race condition:
#include <sys/types.h>
#include <sys/stat.h>
int main(argc,argv){
struct stat *sb;
time_t timer;
lstat("bar.sh",sb);
printf("%d\n",sb->st_ctime);
switch(sb->st_ctime % 2){
case 0: printf("One option\n");
break;
case 1: printf("another option\n");
break;
default: printf("huh\n");
break;
}
return 0;
}
The explanation says:
It seems that the default case of the switch statement
should never be reached, as st_ctime % 2 should always
be 0 or 1. However, if st_ctime % 2 is 1 when the first
case is evaluated, the time may change and st_ctime % 2
may be equal to 0 when the second case is evaluated.
The result is that neither case 1 or case 2 execute,
and the default option is chosen.
I'm not able to understand this part: ... the time may change and st_ctime % 2 may be equal to 0 when the second case is evaluated. The result is that neither case 1 or case 2 execute, and the default option is chosen.
The page doesn't make it clear whether this applies to single or multi-threading.
I read the related SO question, which highlights 64-bit writes are not atomic. In the example above, when switch is evaluating the condition, the time changes, will the evaluation of sb->st_ctime % 2
still come out to something other 0 0r 1 ? (even or odd number ?) Does the problem exists in single-threaded case ?