syscalls

fork() — Linux system interface

Create one child process. Parent and child continue from the call with different return values. Linux normally uses copy-on-write for ordinary private memory; inherited descriptors can share open file descriptions. The child has a distinct PID. Order of execution is not guaranteed. EAGAIN or ENOMEM can prevent creation. In a multithreaded process restrict child operations before exec to async-signal-safe functions. Use _exit in the child when appropriate and reap it with waitpid; never use an unbounded fork loop. 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 <unistd.h>pid_t fork(void);

Return Value

pid_t

Child PID in parent; 0 in child. 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 <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)
int main(void){    int value = 5;    pid_t child = fork();    CHECK(child >= 0);    if (child == 0) {        value = 7;        _exit(value);    }    int status;    pid_t got;    do { got = waitpid(child, &status, 0); } while (got < 0 && errno == EINTR);    CHECK(got == child && WIFEXITED(status));    CHECK(WEXITSTATUS(status) == 7 && value == 5);    printf("parent value=%d; child exit=%d\n", value, WEXITSTATUS(status));    return EXIT_SUCCESS;}
Linux Reference