Skip to content

close()

Purpose

close() releases a file descriptor.

After close(), the file descriptor number may be reused by the kernel for another open file.

#include <unistd.h>

Prototype

int close(int fd);

Parameters

Parameter Description
fd File descriptor to release.

Return Value

Returns 0 on success. Returns -1 on failure and sets errno.

Minimal Example

if (fd >= 0) {
    close(fd);
    fd = -1;
}

Common Pitfalls

  • Using an fd after it has been closed.
  • Closing the same fd twice.
  • Forgetting to remove a closed fd from epoll bookkeeping.
  • Not resetting local fd variables to -1 after cleanup.