TIL: bitwise ǀ and & on open flags in UNIX
published
last modified
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.
They can look like
We can define a combination of these flags using the logical |
like so
which in binary looks like
How does open()
use this to intepret what flags we have set?
Well it uses the &
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
It results in
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
In practice, we can use binary numbers like this to set states and check for states in any system, similar boolean flags.
Contact
If you have any comments or thoughts you can reach me at any of the places below.