Processes & Process Control

the exec family (execve and friends)

fork() gives you a second copy of the same program - but usually you want the new process to run a different program entirely (you forked your shell, but you want to run ls, not another shell). That is what exec does: it takes the current process and replaces everything it is running - the code, the data, the heap, the stack - with a brand-new program loaded from an executable file. The process keeps its identity (same PID, same open files), but the program it is running is swapped out wholesale. Think of an actor who keeps their dressing room (the process) but changes into a completely different costume and script (the program image).

Concretely, a call like execve("/bin/ls", argv, envp) tells the kernel: throw away this process's current address space, load the program at /bin/ls into a fresh image, set up the argument list (argv) and environment (envp), and start executing the new program from its entry point. The key, surprising fact: when exec succeeds it does not return. There is no 'after exec' in the old program, because the old program no longer exists in this process - its memory was discarded. Code after a successful exec() runs only if exec failed (for example, the file was not found), which is why you usually see a perror() and exit right after the call. The 'family' part - execl, execlp, execv, execvp, execve, execve - is just different convenience wrappers around the same idea, varying in how you pass arguments (list vs array) and whether they search the PATH for the program.

Why it matters: exec is the second half of how every program gets launched. The fixed identity (same PID) is what lets a parent track and wait for the child even after the child becomes a different program. exec is also where the environment is passed across the boundary into the new program, and where the new program's argv[0] is set. Understanding that exec replaces the image - rather than starting a separate new process - is what makes the fork-then-exec pattern click.

char *argv[] = { "ls", "-l", NULL }; execvp("ls", argv); perror("execvp"); _exit(127); - if execvp succeeds, this process is now running ls and the perror line never executes; if it reaches perror, exec failed and we report the error and quit.

Code after a successful exec() never runs - reaching it means exec failed.

exec replaces the program but keeps the process: same PID, and (unless marked close-on-exec) the same open file descriptors carry over. It does not create a child - to get a new process and run a new program, you fork first, then exec.

Also called
execveexec functions替換行程映像執行替換