5

I am dealing with file status flags. Among test I performed, I found

#include <stdio.h>
#include "fcntl.h"

int main() {
    const int flag = O_RDONLY;
    printf( "*** Flag O_RDONLY = %5d\n", flag);
    return 0;
}

produces this output

*** Flag O_RDONLY =     0

which is fully consistent with

#define O_RDONLY         00

from fcntl-linux.h.

How can the value zero be used as a flag?

I expect an "atomic" flag to be 2^n (n>=1), and "composite" flags (like O_ACCMODE) to be simply the sum of several atomic flags (which is the same as bitwise-or'ing those atomic flags).
As far as I understand, I cannot "detect" anything, and such flag cannot be ever set. A bitwise-and'ed expression like (stat & O_RDONLY) will always be false.

Related:

How to get the mode of a file descriptor? (I asked this)

1 Answers1

7

Although these are called flags in the documentation, these three are not actually atomic flags that can be combined like the rest. They're mutually exclusive alternative values for the O_ACCMODE bits. You don't use stat & RDONLY to test for it, you use (stat & O_ACCMODE) == O_RDONLY.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Great! Actually, the man page http://man7.org/linux/man-pages/man2/open.2.html first describes the file access modes, and then adds "In addition, zero or more file creation flags and file status flags can be bitwise-or'd in flags...." But it does not mention that file access mode can be bitwise operated on. For me, the word "flag" is an absolute misnomer, and misleading. – sancho.s ReinstateMonicaCellio May 20 '20 at 22:39
  • Related, can you please check https://stackoverflow.com/questions/61909358/how-to-get-the-mode-of-a-file-descriptor/61909773 and give your insight? – Tony Tannous May 21 '20 at 12:01