syscalls

clone() — Linux system interface

The glibc clone wrapper creates a child that starts in a supplied function, using a supplied stack; flags determine resource sharing and the exit signal. The raw clone ABI differs across architectures; clone3 is a distinct interface. This x86_64 example uses only SIGCHLD with no sharing or namespace flags, so it resembles fork with a separate child entry function. Keep stack storage valid until the child terminates; for downward-growing stacks pass its aligned high end. Handle EINVAL for invalid flag combinations, EAGAIN for process limits, ENOMEM for memory limits, and EPERM for forbidden namespace flags. Reap the child. Do not use this example as a general thread library. 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. Linux-specific interface or flags; examples target Linux/glibc on x86_64. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#define _GNU_SOURCE#include <sched.h>int clone(int (*fn)(void *), void *stack, int flags, void *arg, ...);

Parameters & Attributes

NameTypeDescription
fnint (*)(void *)Child entry function.
stackvoid *Child stack pointer; aligned high end on x86_64.
flagsintResource-sharing options and exit signal.
argvoid *Argument to child entry.
optionalvariadicOptional parent_tid, tls, child_tid arguments depend on flags.

Return Value

int

Positive child PID in caller, or -1 with errno. Child executes fn and exits with its return status.

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 <sched.h>#include <signal.h>#include <sys/wait.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)
static int child(void *arg) {    int *value = arg;    int result = *value;    *value = 9;    return result;}
int main(void){    size_t size = 1024u * 1024u;    unsigned char *stack = malloc(size);    CHECK(stack != NULL);    int value = 7;    pid_t pid = clone(child, stack + size, SIGCHLD, &value);    CHECK(pid > 0);    int status; pid_t got;    do { got = waitpid(pid, &status, 0); } while (got == -1 && errno == EINTR);    CHECK(got == pid && WIFEXITED(status) && WEXITSTATUS(status) == 7);    CHECK(value == 7);    free(stack);    puts("clone child exit 7; parent value unchanged; child reaped");    return EXIT_SUCCESS;}
Linux Reference