Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking only the O_RDONLY flag to open(2)

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?

like image 981
FutureShocked Avatar asked Oct 30 '25 22:10

FutureShocked


2 Answers

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_ACCMODE Mask for file access modes.

So you can use code such as ((flags&O_ACCMODE) == O_RDONLY), etc.

like image 72
Mark Plotnick Avatar answered Nov 02 '25 12:11

Mark Plotnick


Use

int open_mode = (flags & O_ACCMODE);

Then you can use checks like:

(open_mode == O_RDONLY)
like image 22
David Schwartz Avatar answered Nov 02 '25 11:11

David Schwartz