Open Flags in UNIX
2kb
Open flags are specified as macros provided to pass to the system call open()
, to define what permissions and types we want to open a file with. These come in the form of binary numbers, and are usually defined as constants.
#define O_RDONLY 0b00000000
#define O_CREAT 0b00000100
#define O_TRUNC 0b00001000
We can define a combination of these flags using the bitwise OR
operator.
O_RDONLY | O_CREAT | O_TRUC
The binary representation of these flags 0b00001100
. How does open()
use this to intepret what flags we have set? It uses the bitwise AND
operator.
Bitmasks
A bitmask is data used in bitwise operations. The &
bitwise operator will set the bit only if both bits are 'on' (i.e 1 and 1).
Using our example above if we &
O_CREATE with our flags, we obtain
00000100 &
00001100
---
00000100
The idea is, if we &
any of the flags with the oflag above and the result is non-zero then we know that flag is set.
This is how we open()
checks for which flags have been set
if (flags & O_CREAT) {
// do something
}
In practice, we can use binary numbers like this to set states and check for states in any system, similar to boolean flags.
Contact
If you have any comments or thoughts you can reach me at any of the places below.