syscalls

accept() — Linux system interface

Remove a pending connection from a listener and return a separate connected descriptor; the listener stays open. Optional peer address output uses an in/out length pointer. On Linux accept returns a socket without the listener's O_NONBLOCK status or FD_CLOEXEC descriptor flag. Use accept4 with SOCK_NONBLOCK and SOCK_CLOEXEC to request those properties at creation. A nonblocking listener is still needed to prevent accept from waiting after a stale readiness event. A nonblocking listener without a queued connection returns EAGAIN or EWOULDBLOCK. Handle EINTR and close each accepted connection independently. 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; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <sys/socket.h>int accept(int sockfd, struct sockaddr *restrict addr, socklen_t *restrict addrlen);

Parameters & Attributes

NameTypeDescription
sockfdintListening socket descriptor.
addrstruct sockaddr *Optional peer address buffer.
addrlensocklen_t *In/out buffer length; NULL when addr is NULL.

Return Value

int

Nonnegative owned descriptor on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <sys/un.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){    struct sockaddr_un a = { .sun_family = AF_UNIX, .sun_path = "demo.sock" };    int s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);    CHECK(s >= 0);    CHECK(bind(s, (struct sockaddr *)&a, sizeof a) == 0);    CHECK(listen(s, 4) == 0);
    int flags = fcntl(s, F_GETFL);    CHECK(flags >= 0 && fcntl(s, F_SETFL, flags | O_NONBLOCK) == 0);    CHECK(accept(s, NULL, NULL) == -1 && (errno == EAGAIN || errno == EWOULDBLOCK));    int c = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);    CHECK(c >= 0);    CHECK(connect(c, (struct sockaddr *)&a, sizeof a) == 0);
    int peer = accept(s, NULL, NULL);    CHECK(peer >= 0 && peer != s);    flags = fcntl(peer, F_GETFL);    CHECK(flags >= 0 && !(flags & O_NONBLOCK));    CHECK(close(peer) == 0);    CHECK(close(c) == 0);    CHECK(close(s) == 0);    CHECK(unlink("demo.sock") == 0);    puts("empty queue EAGAIN; accepted separate blocking socket");    return EXIT_SUCCESS;}
Linux Reference