syscalls

execve() — Linux system interface

Replace the calling process image, normally retaining its PID. This does not create another process. Supply a pathname and NULL-terminated argument and environment arrays; argv[0] conventionally identifies the executable. No PATH search occurs. Descriptors with close-on-exec are closed on success; other descriptors can survive. Typical errors are ENOENT, EACCES, ENOEXEC, E2BIG. Do not continue as though replacement succeeded if the call returns; handle the failure, then terminate a forked child with _exit. The example uses a fixed local executable and empty environment; no user input is interpreted. 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; empty-path error checked on Linux and /bin/sh must be available. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <unistd.h>int execve(const char *path, char *const argv[], char *const envp[]);

Parameters & Attributes

NameTypeDescription
pathconst char *Executable pathname.
argvchar *const []NULL-terminated argument vector.
envpchar *const []NULL-terminated environment vector.

Return Value

int

No normal return 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 <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){    char *const args[] = {"sh", "-c", "exit 9", NULL};    char *const env[] = {NULL};    CHECK(execve("", args, env) == -1 && errno == ENOENT);    pid_t child = fork();    CHECK(child >= 0);    if (child == 0) {        execve("/bin/sh", args, env);        _exit(127);    }    int status;    pid_t got;    do { got = waitpid(child, &status, 0); } while (got < 0 && errno == EINTR);    CHECK(got == child && WIFEXITED(status));    CHECK(WEXITSTATUS(status) == 9);    puts("empty path: ENOENT; replacement exited 9");    return EXIT_SUCCESS;}
Linux Reference