syscalls

close() — Linux system interface

Release a descriptor number; other descriptors referencing the same open file description remain valid. Numbers can be reused immediately. Check the return value, especially for files written to; a successful close does not prove durable storage. On Linux do not blindly retry close after an error, including EINTR: the descriptor may already have been released and reused. EBADF identifies an invalid descriptor; EIO, ENOSPC or EDQUOT may expose delayed failures. Coordinate descriptor ownership across threads. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; the no-retry guidance is specific to Linux close semantics. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <unistd.h>int close(int fd);

Parameters & Attributes

NameTypeDescription
fdintOwned open descriptor to release.

Return Value

int

0 on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _DEFAULT_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    int f = open("/dev/null", O_RDONLY | O_CLOEXEC);    CHECK(f >= 0);    int other = dup(f);    CHECK(other >= 0);    CHECK(close(f) == 0);    char b;    CHECK(read(f, &b, 1) == -1 && errno == EBADF);    CHECK(read(other, &b, 1) == 0);    CHECK(close(other) == 0);    puts("closed descriptor rejected; duplicate still valid");    return EXIT_SUCCESS;}
Linux Reference