Skip to content

fcntl()

Purpose

fcntl() performs file descriptor control operations.

In these labs, it is most commonly used to enable non-blocking I/O and set close-on-exec behavior.

#include <fcntl.h>
#include <unistd.h>

Prototype

int fcntl(int fd, int cmd, ...);

Common Commands

Command Purpose
F_GETFL Get file status flags.
F_SETFL Set file status flags, such as O_NONBLOCK.
F_GETFD Get file descriptor flags.
F_SETFD Set file descriptor flags, such as FD_CLOEXEC.

Minimal Example

int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
    return -1;

if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
    return -1;

Common Pitfalls

  • Overwriting existing flags instead of OR-ing with them.
  • Confusing file status flags (O_NONBLOCK) with descriptor flags (FD_CLOEXEC).
  • Forgetting that non-blocking behavior changes read() and write() error handling.