I'm checking the flags sent to the open(2) call against permissions I've set up in some meta files. The perms here are related to the octal values typically sent to calls like chmod. I want the if block to be entered when perms is not matched by the relevant flag.
if((perms == 4 && !(flags & O_RDONLY)) ||
   (perms == 2 && !(flags & O_WRONLY)) ||
   (perms == 6 && !(flags & O_RDWR))) 
I expected this to work, and it does just fine in the the O_WRONLY and O_RDWR. However, the actual value of O_RDONLY is 0, so the & operator will return false for every value. Unfortunately, removing the negation will lead to the undesired behavior of every perms value of 4 skipping the if block. How can I achieve my goal here?
Originally, the second argument to 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 includes the following definition:
Mask for use with file access modes is as follows:
O_ACCMODEMask for file access modes.
So you can use code such as ((flags&O_ACCMODE) == O_RDONLY), etc.
Use
int open_mode = (flags & O_ACCMODE);
Then you can use checks like:
(open_mode == O_RDONLY)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With