仅检查 O_RDONLY 标志以打开 (2)

Checking only the O_RDONLY flag to open(2)

我正在根据我在某些元文件中设置的权限检查发送到 open(2) 调用的标志。这里的 perms 与通常发送给 chmod 等调用的八进制值有关。我希望在 perms 与相关标志不匹配时输入 if 块。

if((perms == 4 && !(flags & O_RDONLY)) ||
   (perms == 2 && !(flags & O_WRONLY)) ||
   (perms == 6 && !(flags & O_RDWR))) 

我希望它能工作,并且在 O_WRONLY 和 O_RDWR 中效果很好。但是,O_RDONLY 的实际值为 0,因此 & 运算符将为每个值 return false。不幸的是,删除否定将导致每个 perms 值 4 跳过 if 块的不良行为。我怎样才能在这里实现我的目标?

使用

int open_mode = (flags & O_ACCMODE);

然后您可以使用如下检查:

(open_mode == O_RDONLY)

最初,open was called mode and was documented as being 0, 1, or 2. Later on, the argument was renamed oflag, and it could now contain flags in addition to the access mode. The possible values for the mode were kept the same, though, and symbolic names were given for them, with the caution that, unlike flags, only one of O_RDONLY, O_WRONLY, and O_RDWR could be used. The POSIX standard 的第二个参数包含以下定义:

Mask for use with file access modes is as follows:
O_ACCMODE Mask for file access modes.

所以可以使用((flags&O_ACCMODE) == O_RDONLY)等代码