syscalls

recv() — Linux system interface

Read incoming bytes into a caller-owned buffer. Stream reads can be short and do not preserve message boundaries. For a positive-length stream request, zero normally means orderly peer write shutdown after pending data is consumed; datagrams may contain zero bytes. MSG_DONTWAIT is a per-call nonblocking flag; EAGAIN or EWOULDBLOCK means no data now, not EOF. With Linux MSG_TRUNC on supported message-oriented sockets, the reported message length may exceed the buffer capacity; consume only bytes actually stored. A zero-length request on a stream also can return zero without indicating shutdown. Avoid interpreting binary data as a NUL-terminated string without validation. 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>ssize_t recv(int sockfd, void *buf, size_t len, int flags);

Parameters & Attributes

NameTypeDescription
sockfdintSocket descriptor.
bufvoid *Writable buffer.
lensize_tBuffer capacity in bytes.
flagsintPer-call receive flags.

Return Value

ssize_t

Normally the received byte count; with Linux MSG_TRUNC on supported message sockets it may report the full message size beyond the supplied buffer. Zero can mean stream EOF, a zero-size datagram or a zero-length stream request. Failure returns -1 with errno set.

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>
/* 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[2]; char b[8];    CHECK(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, f) == 0);    CHECK(recv(f[1], b, sizeof b, MSG_DONTWAIT) == -1 && (errno == EAGAIN || errno == EWOULDBLOCK));    CHECK(send(f[0], "z", 1, 0) == 1);    CHECK(shutdown(f[0], SHUT_WR) == 0);    CHECK(recv(f[1], b, sizeof b, 0) == 1 && b[0] == 'z');    CHECK(recv(f[1], b, sizeof b, 0) == 0);    CHECK(close(f[0]) == 0 && close(f[1]) == 0);    puts("EAGAIN; short receive=1; EOF=0");    return EXIT_SUCCESS;}
Linux Reference