Search code examples
cbitwise-operatorsinotifybitwise-and

C program using inotify help in understanding code


I was referring the man page for inotify and I came across this piece of code

               if (event->mask & IN_ISDIR)
                   printf(" [directory]\n");
               else
                   printf(" [file]\n");

where event is a pointer to struct inotify_event.

  • I couldn't understand this particular line if (event->mask & IN_ISDIR) and why a bitwise AND is used here.

  • How was it determined that the bitwise AND is supposed to be used here and nothing else? It was not mentioned in the man page for inotify.


Solution

  • This bitwise AND is masking out a specific bit (IN_ISDIR). It is testing whether or not this one bit is set or not. If this bit is set in event->mask, it evaluates to true.

    For example,

    #include <stdio.h>
    
    #define FIRST_BIT  1
    #define SECOND_BIT 2
    #define THIRD_BIT  4
    
    int main() {
      int x = 3;  /* 3 in binary is 011 */
    
      if ( x & FIRST_BIT )
        printf("First bit is set\n");
      if ( x & SECOND_BIT )
        printf("Second bit is set\n");
      if ( x & THIRD_BIT )
        printf("Third bit is set\n");
    }
    

    will give the output

        First bit is set
        Second bit is set
    

    From inotify.h:

    #define IN_ISDIR          0x40000000    /* event occurred against dir */
    

    This value has only one bit set. (In binary, this is 01000000000000000000000000000000.) A bitwise AND with this (0x40000000) and some variable will evaluate to either 0 (if the variable has a 0 here), or 0x40000000 if the variable has a 1 in the same place. Any non-zero value is considered "true".

    Logically, it is testing if the event was from a directory (instead of a file).