0

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 ?

Community
  • 1
  • 1
Jake
  • 16,329
  • 50
  • 126
  • 202
  • Race conditions normally occur when one thread changes data that another thread is currently operating on. I think something is missing from the example - a timer that actually refreshes the contents of sb (which would be done on another thread). Another question in this scenario is wether or not switch would calculate sb->st_ctime % 2 for each case because I'd assume that the compiler would do that calculation only once and compare the results to the cases but that is I guess up to the compiler implementation. – Oliver Ulm Apr 01 '16 at 05:32
  • The way it's described however is clearly that when the first case is evaluated sb->st_ctime %2 would be 1 and when the check is performed again sb->st_ctime % 2 would be 0 as the value has changed in the meantime (due to another thread changing the data). – Oliver Ulm Apr 01 '16 at 05:35

0 Answers0