exec · system call

Also known as: exec system call · execve

On this page 8

exec is the system call family in Linux that replaces the program image of the calling process with a new executable, while the process keeps its process ID, parent and most of its kernel bookkeeping. The kernel entry point is execve, and the C library wrappers such as execl, execvp and execle all end in that single exec system call.

In the topic of Linux processes, exec is the second half of the classic fork-and-exec model: fork creates a copy of a process, and exec turns that copy into a different program. Every shell command, service start and container launch depends on this pair, so understanding exec explains how new programs actually begin running.

How execve replaces a process image

A successful execve call discards the old address space and builds a new one from the target file. The kernel opens the file, checks execute permission, reads the header, and selects a binary format handler: ELF for native programs, the script handler for files that begin with #!, or a registered binfmt_misc handler for other formats.

For an ELF binary the kernel maps the text and data segments, sets up a fresh stack, copies the argument vector and environment onto it, and, for dynamically linked programs, maps the dynamic loader named in the PT_INTERP header. Control then jumps to the loader or to the program entry point. execve never returns on success; it returns -1 with errno set only when the replacement fails.

The steps below summarize the work the kernel performs during one exec call.

StageWhat the kernel doesTypical failure
Path lookupResolves the file name and checks permissionsENOENT or EACCES
Format detectionReads the header and picks a handlerENOEXEC for unknown formats
Point of no returnReleases the old memory mapFatal signal if later steps fail
Image setupMaps segments, stack, arguments and environmentE2BIG for oversized arguments
Credential updateApplies set-user-ID bits and file capabilitiesIgnored under nosuid mounts
StartTransfers control to the loader or entry pointCrash inside the new program
Main stages of an execve call

What survives an exec call

exec changes the program but not the process identity. The process ID, parent process ID, session, process group, current directory, resource limits and open file descriptors all carry over. This persistence is exactly what lets a shell set up redirections and pipes before starting a command.

Other state is reset because it belonged to the old program. Memory mappings, signal handlers, threads and timers cannot survive, since the code they refer to no longer exists. The following table lists the most important attributes and their fate.

AttributeAfter execReason
Process ID and parentPreservedThe process itself continues
Open file descriptorsPreserved unless close-on-execEnables redirection and pipes
Signal handlersReset to defaultHandler code is gone
Ignored signalsRemain ignoredNo code reference involved
Signal mask and pending signalsPreservedKernel-level state
Memory mappings and threadsDiscardedNew address space is built
Resource limits and nice valuePreservedPer-process kernel settings
Effective user IDMay changeSet-user-ID bit on the file
Process attributes across exec

The close-on-exec flag (FD_CLOEXEC, or O_CLOEXEC at open time) marks descriptors that the kernel should close automatically during exec. Setting it by default is a key security practice, because a leaked descriptor can give a less trusted child program access to files, sockets or pipes it was never meant to see.

The exec function family and its variants

The C library exposes several exec wrapper functions whose names encode how they receive arguments. The letter l means a list of arguments, v means a vector (array), p means the program is searched in PATH, and e means the caller supplies an explicit environment.

FunctionArgumentsPATH searchEnvironment
execveArrayNoExplicit
execlListNoInherited
execlpListYesInherited
execleListNoExplicit
execvArrayNoInherited
execvpArrayYesInherited
fexecveArray plus descriptorNoExplicit
Common exec variants

Linux also provides execveat, which resolves the path relative to a directory descriptor and, with the AT_EMPTY_PATH flag, can run a file through an already open descriptor. This closes the race window between checking a file and executing it, a class of bug known as TOCTOU.

How exec relates to fork, clone and posix_spawn

exec does not create processes; it only changes what an existing process runs. Creating a process is the job of fork, vfork or clone. A shell typically calls fork, adjusts descriptors and signals in the child, and then calls exec, while the parent waits for the child to finish and reaps it to avoid a zombie process.

The comparison below shows where each primitive fits in the process lifecycle.

PrimitiveCreates a processRuns a new programTypical use
forkYesNoDuplicate the caller
execNoYesReplace the current program
vforkYesNoFast fork followed by exec
cloneYesNoThreads, namespaces, containers
posix_spawnYesYesCombined create and run
Process creation and replacement primitives

posix_spawn combines both steps and lets the library use the cheapest method available, often vfork or clone with shared memory. For large processes it avoids copying page tables, which makes it noticeably faster than a plain fork followed by exec when memory footprints reach gigabytes.

Practical uses of exec in Linux

Beyond shells, exec appears wherever a program must hand control to another program without creating a new process. Wrapper scripts and container entry points rely on it so that the final program becomes the process that receives signals.

  • The shell builtin exec replaces the shell itself, which is why exec "$@" ends many container entry-point scripts and makes the application PID 1 inside the container.
  • Privilege-dropping launchers change user and group IDs, set resource limits, and then exec the target, so the target never runs with elevated rights.
  • Service managers fork, configure cgroups and namespaces, and exec the service binary with a controlled environment.
  • Tools such as nohup, nice and env adjust one attribute and then exec the requested command.

Common mistakes and security pitfalls

Many exec bugs come from assumptions about state that silently carries over or from code that runs after a failed call. The table below pairs frequent symptoms with their usual causes and fixes.

SymptomCauseFix
Child holds a socket openDescriptor lacked close-on-execOpen with O_CLOEXEC
Program runs twiceCode after a failed exec continuedCall _exit after exec fails
Wrong binary is startedUntrusted PATH with execvpUse absolute paths
Container ignores SIGTERMShell wrapper did not execEnd the script with exec
Arguments are rejectedTotal size exceeds the limitPass data through a file
Frequent exec problems

A child must call _exit rather than exit after a failed exec, so that inherited stdio buffers are not flushed twice. Passing user input to sh -c instead of an argument array invites command injection, which is why security reviews favor execve with an explicit argument vector.

Stripped to the essentials

A running program in Linux lives inside a container called a process. exec lets that process swap out its program for a completely different one. Think of an actor who keeps the same dressing room and name tag. The actor simply changes into a new role.

The process keeps its number and its open files. It also keeps its place in the family tree. The old program, however, disappears for good. Starting almost any program on Linux works this way. First a copy of a process is made. Then exec turns the copy into the program you asked for.

Where it is applied

A platform team packages a web application in a container. The image starts with a short shell script that reads secrets, writes a configuration file, and finally runs the application server. In the first version the script simply called the server binary, so the shell remained PID 1 and the server ran as its child.

During rolling deployments the orchestrator sent SIGTERM to PID 1, but the shell did not forward it. Each pod waited the full 30-second grace period before being killed, and in-flight requests were cut off abruptly. The team changed the last line to exec /usr/local/bin/server, so the server replaced the shell and received the signal directly.

After the change, pods shut down in under two seconds, connections drained cleanly, and deployment time for a forty-pod service fell by more than ten minutes.