How to make sense of O_RDONLY = 0?

你离开我真会死。 提交于 2020-05-23 16:25:26

问题


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:


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.



来源:https://stackoverflow.com/questions/61923703/how-to-make-sense-of-o-rdonly-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!