networking · beginner · ~15 min

Set the non-blocking flag

Add a flag bit with bitwise OR.

Challenge

Add the O_NONBLOCK bit to an fd's flags — the bit you OR in before fcntl(fd, F_SETFL, ...).

Task

Implement int add_nonblock(int flags, int o_nonblock).

Input

  • flags: the current file-status flags.
  • o_nonblock: the O_NONBLOCK bit value.

Output

Return flags with the o_nonblock bit OR-ed in.

Example

add_nonblock(2,    2048)  ->  2050
add_nonblock(2050, 2048)  ->  2050   (already set: idempotent)

Edge cases

  • OR-ing a bit that is already set leaves the value unchanged.

Input format

flags: current file-status flags; o_nonblock: the O_NONBLOCK bit.

Output format

flags with the o_nonblock bit OR-ed in.

Constraints

Use bitwise OR; setting an already-set bit is a no-op.

Starter code

int add_nonblock(int flags, int o_nonblock) {
    /* TODO */
    return flags;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.