TIL: bitwise ǀ and & on open flags in UNIX

published

last modified

systems
linux

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

open_flags.c
#define O_RDONLY        0b00000000 
#define O_CREAT         0b00000100 
#define O_TRUNC         0b00001000

We can define a combination of these flags using the logical | like so

O_RDONLY | O_CREAT | O_TRUC
open flags

which in binary looks like

0b00001100
binary representation of an open flag

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

00000100 &
00001100

It results in

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 boolean flags.

Contact

If you have any comments or thoughts you can reach me at any of the places below.