Master Linux Process Creation, Fork, Exec, and Simple Shell – A Hands‑On Guide
This tutorial walks you through Linux process creation with fork, explains copy‑on‑write mechanics, details process termination, waiting, and program replacement using exec families, and culminates in building a basic shell, complete with code examples and visual illustrations.
1. Process Creation
In Linux, the fork function creates a new child process from an existing one. The child receives a return value of 0, while the parent receives the child's PID; on error, -1 is returned.
#include <unistd.h>
pid_t fork(void);
// returns 0 in child, child's PID in parent, -1 on errorAfter fork, the kernel allocates a new PCB and address space, copies the parent’s data structures, adds the child to the process list, and returns to the scheduler.
Both parent and child can diverge using an if‑else statement to run different code paths.
Write‑On‑Copy (COW)
Before creating the child, the kernel marks all pages of the parent as read‑only. When the child attempts to write, a page fault occurs; the kernel then allocates a new page, copies the data, and updates the page table, allowing the child to modify its own copy without affecting the parent.
After the write, the page’s permissions are changed back to read‑write.
2. Process Termination
The main function’s return value becomes the process exit code (0 for success, non‑zero for failure). You can also call exit or the system call _exit. The latter does not flush stdio buffers, so output may be lost.
int main() {
printf("i am child process, pid:%d, ppid:%d
", getpid(), getppid());
exit(7); // normal termination, buffers flushed
}When a process crashes (e.g., dereferencing NULL), the kernel sends a signal (e.g., SIGSEGV = 11) which terminates the process.
3. Process Waiting
The parent can wait for a child using wait or waitpid. These calls retrieve the child’s exit status and signal information.
pid_t pid = fork();
if (pid == 0) {
// child work
exit(0);
} else {
int status;
pid_t rid = waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("child exited with code %d
", WEXITSTATUS(status));
}
}The status integer encodes both exit code (bits 8‑15) and termination signal (bits 0‑6). Use macros WIFEXITED and WEXITSTATUS for readability.
Waiting for Multiple Children
Loop with waitpid(-1, ...) to reap any child as it finishes.
Non‑Blocking Wait
Pass WNOHANG to waitpid so the call returns immediately if no child has exited, allowing the parent to perform other work.
4. Program Replacement (exec)
The exec family replaces the current process image with a new program. After a successful exec, the original code never runs again; only the new program continues.
Common variants: execl(path, arg0, arg1, ..., NULL) – list of arguments. execlp(file, arg0, ..., NULL) – searches PATH. execv(path, argv) – vector of arguments. execvp(file, argv) – vector + PATH search. execle(path, arg0, ..., NULL, envp) – custom environment. execvpe(file, argv, envp) – vector + PATH + custom env.
Example of replacing a child with ls:
pid_t id = fork();
if (id == 0) {
printf("pid: %d, exec begin
", getpid());
execlp("ls", "ls", "-a", "-l", NULL);
// not reached on success
}5. Simple Shell Implementation
The final example builds a minimal shell that parses user input, handles built‑in commands ( cd, echo), and executes external programs via fork + execvp. It also tracks the last exit code for echo $? support.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int main() {
char line[1024];
char *argv[64];
while (1) {
printf("$ ");
if (!fgets(line, sizeof line, stdin)) break;
line[strcspn(line, "
")] = '\0';
// split
int i = 0; argv[i] = strtok(line, " ");
while (argv[i]) argv[++i] = strtok(NULL, " ");
if (!argv[0]) continue;
if (strcmp(argv[0], "cd") == 0) { chdir(argv[1] ? argv[1] : "."); continue; }
if (strcmp(argv[0], "exit") == 0) break;
pid_t pid = fork();
if (pid == 0) { execvp(argv[0], argv); _exit(127); }
else { int status; waitpid(pid, &status, 0); }
}
return 0;
}This shell demonstrates core OS concepts covered earlier: process creation, waiting, and program replacement.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
