[whb@bite-alicloud test]$ ls
client.c readme.md server.c utility.hshell 收到 ls 之后,自己并没有变成 ls。它先 fork 出一个子进程,子进程 exec 成 ls,父进程 wait 到子进程退出,再打印下一个提示符。这一串动作分别对应 fork、exec、wait、exit 四个接口,每个接口都有自己的返回值约定和状态编码。
fork 的返回值写进两个进程的寄存器
#include <unistd.h>
pid_t fork(void);fork 从已存在的进程创建一个新进程,原进程是父,新进程是子。返回值有三种:子进程里是 0,父进程里是子进程的 PID,出错是 -1。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
printf("Before: pid is %d\n", getpid());
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
printf("After: pid is %d, fork return %d\n", getpid(), pid);
sleep(1);
return 0;
}在终端上跑,输出里有一行 Before、两行 After。子进程没有打印 Before,因为它在 fork 之后才存在;父进程和子进程都从 fork 的下一行继续执行,谁先被调度由调度器决定。

内核在 fork 里做四件事:给子进程分配新的 task_struct 和地址空间描述;复制父进程的部分内核数据结构;把子进程挂进进程列表和调度队列;让父子各自从 fork 返回。返回值不是函数“返回了两次”,而是两个执行流各自从调用点恢复,内核把子进程的返回值写 0、父进程的写子 PID,分别放在各自的 rax 里。
子进程返回 0 是因为它只需要知道“我是子进程”,自己的 PID 用 getpid() 随时能取;父进程需要子 PID 才能在 waitpid 里指定等哪一个孩子。让父进程拿 PID、子进程拿 0,是最省信息的一种约定。
fork 失败通常因为系统进程总数到上限,或当前用户的进程数超限。常见用法有两种:父进程复制自己,让子进程处理另一段逻辑;子进程 fork 后立刻 exec 一个全新的程序。
vfork 是另一套创建接口:它不复制地址空间,子进程直接借用父进程的地址空间,并保证子进程先运行,直到子进程调用 exec 或 _exit 才把控制权还给父进程。它适合“fork 完马上 exec”这一种场景;如果在 vfork 之后改父进程的变量,父子会互相踩,所以现代代码基本用 fork 加写时拷贝。子进程在 vfork 之后不能用 exit,因为 exit 会刷新父进程共享的 stdio 缓冲,应该用 _exit。
写时拷贝让 fork 很快返回
fork 复制的是页表,不是物理页。父子进程的页表先指向同一批物理页,这些页被标成只读;任何一方写入时触发页错误,内核才复制被写的那一页,改页表并打开写权限。没有写入的页一直共享。这个机制叫写时拷贝(copy-on-write,COW)。

COW 的价值在于把复制的成本推迟到真正需要时。fork 可以快速返回,进程池、shell 这类频繁创建子进程的场景不用为一份可能立刻被 exec 丢弃的地址空间付费;只有确实写入的页才复制,整机内存利用率也更高。父子进程的独立性由 COW 保证:一方改自己的变量,另一方看不到。
退出码只有低 8 位能穿过 wait
进程终止的本质是释放资源:代码、数据、打开的文件、地址空间和 task_struct 都要回收。退出分三种情况:运行完毕结果正确、运行完毕结果不正确、异常终止。正常终止可以从 main 返回、调用 exit、调用 _exit;异常终止通常是被信号杀死,例如 Ctrl+C 发出的 SIGINT。
$? 打印上一条命令的退出状态。0 表示成功,非 0 表示某种失败。常见约定:
| 退出码 | 含义 |
|---|---|
| 0 | 成功 |
| 1 | 通用错误 |
| 2 | 命令或参数使用不当 |
| 126 | 找到了但无法执行(权限或格式问题) |
| 127 | 没找到命令,通常是 PATH 不对 |
| 128+n | 被编号为 n 的信号终止 |
| 130 | 被 SIGINT(Ctrl+C)终止 |
| 143 | 被 SIGTERM 终止 |
| 255 | exit(-1) 的结果;更大的值按 256 取模 |
exit 的参数是 int,但内核只保留最低 8 位。exit(257) 是 0x101,父进程读到 1;exit(-1) 读到 255;exit(300) 是 0x12C,读到 44。业务错误码不要超过 255,超出的高位会被无声截断。
exit 和 _exit 的区别在清理工作:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("hello");
exit(0);
}#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("hello");
_exit(0);
}第一段能打印 hello,因为 exit 在进入内核前刷新了 stdout 缓冲;第二段什么都不打印,_exit 直接终止进程,缓冲区里的内容没有机会送出去。exit 做三件事:执行 atexit 或 on_exit 注册的清理函数、关闭所有打开的流并把缓冲数据写入、调用 _exit。
课件的 exit 原型写的是 #include <unistd.h>。exit 声明在 <stdlib.h>,_exit 才在 <unistd.h>;两个头文件混用,在严格编译选项下会报隐式声明。
return n 只有在 main 里才等价于 exit(n):C 标准规定 main 返回到宿主环境时,效果等同于以返回值调用 exit。在普通函数里 return 只返回给调用者,不会终止进程。
课件还写“可以使用 strerror 获取退出码对应的描述”。strerror 的参数是 errno,把 ENOENT、EACCES 这类错误号翻译成文字,它不认识程序自己约定的 0、1、2 退出码。系统调用失败后先看 errno,再用 perror 或 strerror(errno);退出码的含义由程序自己定义。
wait 回收的是 PCB,拿回的是状态位图
子进程退出后,如果父进程不读退出状态,子进程会停在 Z,task_struct 一直占着内存和 PID。wait 和 waitpid 做两件事:回收子进程的内核资源,把退出信息交给父进程。
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);wait 等任意一个子进程,成功返回被回收子进程的 PID,失败返回 -1。waitpid 更细:
pid 取值 | 等谁 |
|---|---|
> 0 | 等 PID 等于该值的那个子进程 |
-1 | 等任意一个子进程,等价于 wait |
0 | 等当前进程组里的任意子进程 |
< -1 | 等进程组 ID 等于 -pid 的任意子进程 |
status 是输出型参数,传 NULL 表示不关心。options 为 0 时阻塞等待;WNOHANG 表示非阻塞,如果没有已退出的子进程就立刻返回 0。
status 不能当普通整数读,它是一张 16 位位图:

WIFEXITED(status):是否正常退出;WEXITSTATUS(status):正常退出时取低 8 位里的退出码;WIFSIGNALED(status):是否被信号杀死;WTERMSIG(status):被信号杀死时取信号编号;WCOREDUMP(status):是否产生了 core 文件。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
sleep(2);
exit(10);
}
int status = 0;
pid_t ret = wait(&status);
if (ret < 0) {
perror("wait");
return 1;
}
if (WIFEXITED(status))
printf("child %d exit code: %d\n", ret, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("child %d killed by signal: %d\n", ret, WTERMSIG(status));
return 0;
}把子进程里的 exit(10) 改成 sleep(20),在另一个终端 kill -9 子进程,父进程会走 WIFSIGNALED 分支,打印信号 9。
非阻塞等待适合父进程还要做别的事的场景:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
sleep(5);
exit(1);
}
int status = 0;
pid_t ret = 0;
while ((ret = waitpid(pid, &status, WNOHANG)) == 0) {
printf("child is still running\n");
sleep(1);
}
if (ret > 0 && WIFEXITED(status))
printf("child exit code: %d\n", WEXITSTATUS(status));
else if (ret < 0)
perror("waitpid");
return 0;
}waitpid 返回 0 表示“孩子还在跑,这次没有可回收的”,不是出错;返回 -1 才是出错,例如 pid 不是自己的子进程时会得到 ECHILD。
一个有多个子进程的父进程,通常在循环里回收:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
for (int i = 0; i < 3; i++) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return 1;
}
if (pid == 0) {
sleep(i + 1);
exit(i);
}
}
int status = 0;
pid_t ret;
while ((ret = waitpid(-1, &status, 0)) > 0) {
if (WIFEXITED(status))
printf("child %d exit %d\n", ret, WEXITSTATUS(status));
}
if (ret < 0 && errno == ECHILD)
printf("all children reaped\n");
return 0;
}循环在 ret == -1 && errno == ECHILD 时结束,表示所有孩子都回收完了。回收顺序不一定等于创建顺序,wait 返回的是“任意一个已经退出的孩子”。不想阻塞时,把 options 换成 WNOHANG,返回 0 就先去干别的事;也可以用 SIGCHLD 信号通知父进程“有孩子状态变了”,再到信号处理函数或主循环里回收。
exec 换的是地址空间,不换 PID
子进程 fork 之后执行的还是父进程的代码。要跑一个完全不同的程序,用 exec 系列函数:它们把当前进程的用户空间代码和数据整体替换成新程序,从新程序的入口开始执行。exec 不创建新进程,PID、父进程关系、已经打开的文件描述符都保留。
六个函数的原型都在 <unistd.h>:
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ...); /* 最后还要跟 char *const envp[] */
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);命名规律:l 表示参数按列表一个个写,v 表示参数装进数组;p 表示按 PATH 搜索文件,不带 p 就要给完整路径;e 表示自己提供环境表,不带 e 就继承当前环境。

| 函数 | 参数形式 | 是否搜 PATH | 环境表 |
|---|---|---|---|
execl | 列表 | 否 | 继承 |
execlp | 列表 | 是 | 继承 |
execle | 列表 | 否 | 自己给 |
execv | 数组 | 否 | 继承 |
execvp | 数组 | 是 | 继承 |
execve | 数组 | 否 | 自己给 |
#include <stdio.h>
#include <unistd.h>
int main(void)
{
char *const argv[] = { "ps", "-ef", NULL };
char *const envp[] = { "PATH=/bin:/usr/bin", "TERM=console", NULL };
execve("/bin/ps", argv, envp);
perror("execve");
return 1;
}exec 成功时不会返回,后面的代码没有机会执行;只有失败才返回 -1 并设置 errno,所以“成功没有返回值,失败才有返回值”这句话是对的。课件的示例把六个函数连续写在同一段代码里,成功时只有第一个会执行。
exec 保留打开的文件描述符,这一点和重定向配合得很紧:shell 子进程先 dup2 把 1 号槽位换成目标文件,再 exec 新程序,新程序的 printf 仍然往 1 号写,于是落进目标文件。文件描述符表不属于被替换的代码和数据,所以它能跨过 exec 继续存在。
课件里 execle("ps", "ps", "-ef", NULL, envp) 这行有路径问题:execle 的第一个参数是 path,它不搜索 PATH,传 "ps" 会得到 ENOENT,要写成 "/bin/ps"。带 p 的 execlp、execvp 才可以只写程序名。execve 是真正的系统调用,位于 man 第 2 节;其余五个在 man 第 3 节。
一个 shell 的循环只有五步
shell 对每条命令做的事可以压成五步:打印提示符并读入一行;按空格拆成 argv;fork 出子进程;子进程 execvp 执行命令;父进程 waitpid 等它退出。cd、exit、export 这类命令必须由 shell 自己执行,因为子进程改自己的当前目录或环境表,父进程看不到。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define LINE_MAX 1024
#define ARGV_MAX 64
int main(void)
{
char line[LINE_MAX];
char *argv[ARGV_MAX];
char host[256];
int last = 0;
if (gethostname(host, sizeof(host)) != 0)
strcpy(host, "localhost");
while (1) {
char cwd[LINE_MAX];
if (getcwd(cwd, sizeof(cwd)) == NULL)
strcpy(cwd, "?");
const char *user = getenv("USER");
printf("[%s@%s %s]%c ", user ? user : "user", host, cwd,
geteuid() == 0 ? '#' : '$');
fflush(stdout);
if (fgets(line, sizeof(line), stdin) == NULL)
break;
line[strcspn(line, "\n")] = '\0';
if (line[0] == '\0')
continue;
int argc = 0;
for (char *tok = strtok(line, " \t"); tok && argc < ARGV_MAX - 1;
tok = strtok(NULL, " \t"))
argv[argc++] = tok;
argv[argc] = NULL;
if (argc == 0)
continue;
if (strcmp(argv[0], "exit") == 0)
break;
if (strcmp(argv[0], "cd") == 0) {
const char *dir = argv[1] ? argv[1] : getenv("HOME");
if (dir == NULL)
dir = "/";
if (chdir(dir) == 0)
last = 0;
else {
perror("cd");
last = 1;
}
continue;
}
if (strcmp(argv[0], "echo") == 0) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "$?") == 0)
printf("%d", last);
else
printf("%s", argv[i]);
if (i < argc - 1)
printf(" ");
}
printf("\n");
last = 0;
continue;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
continue;
}
if (pid == 0) {
execvp(argv[0], argv);
perror(argv[0]);
_exit(127);
}
int status = 0;
if (waitpid(pid, &status, 0) > 0) {
if (WIFEXITED(status))
last = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
last = 128 + WTERMSIG(status);
}
}
return 0;
}gcc -g -Wall myshell.c -o myshell
./myshell运行后输入 ls、cd /tmp、pwd、echo $?、exit。cd 改的是 shell 自己的当前目录,pwd 看到的路径跟着变;ls 在子进程里执行,退出码通过 waitpid 回到 last,echo $? 再把它打印出来。execvp 失败时子进程用 _exit(127) 退出,父进程拿到的就是 127,和 bash 的约定一致。这个 echo 只处理 $? 和普通字符串,没有做 $NAME 展开、引号解析和管道,完整的 shell 还要把这些补上。
从函数和进程的角度看,fork/exec 像函数调用的 call,exit/wait 像 return:参数通过 argv 和环境表传给新程序,结果通过退出码回到父进程。区别在于进程之间有独立的地址空间,跨过去之后原程序的栈和局部变量不再存在,调用关系由内核和 wait 维持。
还没有评论 — 第一条由你来留。