目录
正在加载目录…
正在阅读专栏 OSTEP 操作系统专栏 第 3 篇 · 共 62 篇 · 5%

OSTEP:Process API

发布于 2026-09-17 21:39 · 最后编辑于 2026-09-17 22:08 · 版本 v2 · 字数 9,902 · 预计阅读 20 分钟 👁 16 次阅读

OSTEP:Process API

本篇对应 OSTEP Version 1.10 的 “Interlude: Process API”。UNIX 用 fork() 创建近似副本,用 wait() 等待 child,用 exec() 替换当前 process 的 program;三者组合构成 shell 的基础。

类型与定位

  • 笔记类型:教程/实践
  • 翻译基准:官方 cpu-api.pdf,Version 1.10。
  • 格式说明:Figure 5.1–5.4 的代码、命令和输出按原顺序保留;源文档没有独立图片文件。

TL;DR

  • fork() 返回两次:parent 得到 child PID,child 得到 0。
  • wait() 让 parent block,直到 child 完成。
  • exec() 不创建新 process,而是替换当前 process 的 program image;成功时不返回。
  • shell 通过 fork() → exec() → wait() 运行命令,并在 exec 前修改 file descriptors 实现 redirection 和 pipes。

ASIDE:Interludes

Interlude 会讨论更 practical 的 systems 内容,特别是 operating system APIs 及其使用方式。如果你不喜欢 practical things,理论上可以跳过;不过 practical skills 在 real life 中通常很有用,companies 一般不会因为你缺少 practical skills 而雇用你。

名词解释

名词含义本篇对应物
fork创建 calling process 的近似副本parent/child 分支
child由 fork 创建的新 processrc == 0
parent创建 child 的 processrc > 0
exec替换当前 programexecvp("wc", myargs)
wait等待 child 完成wait(NULL)
file descriptor访问 file/device 的整数句柄STDOUT_FILENO
signal发送给 process 的异步事件SIGINT、SIGTSTP

目录

章节内容
5.1 fork创建 process
5.2 wait等待 child
5.3 exec替换 program
5.4 API 的动机shell、redirection、pipes
5.5 Process Control and Userssignals 与权限
5.6 Useful Toolsman、ps、top、root

5.1 The fork() System Call

本章要解决的问题是:OS 应该提供什么样的 process creation 与 process control interfaces,才能同时获得 powerful functionality、易用性和 high performance?

fork() 用于创建新的 process。不过要先提醒一句:这大概是你会调用的最奇怪的 routine 之一。calling process 会被复制成一个几乎相同的 process,之后 parent 和 child 都从 fork() 返回。

脚注:好吧,我们承认并不能确定这一点——谁知道你趁没人看时会调用什么 routine?不过无论你的 routine-calling pattern 多么 unusual,fork() 都相当奇怪。

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    printf("hello (pid:%d)\n", (int) getpid());
    int rc = fork();
    if (rc < 0) { // fork failed
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) { // child (new process)
        printf("child (pid:%d)\n", (int) getpid());
    } else { // parent goes down this path (main)
        printf("parent of %d (pid:%d)\n", rc, (int) getpid());
    }
    return 0;
}

Figure 5.1:调用 fork()(p1.c)

text
prompt> ./p1
hello (pid:29146)
parent of 29147 (pid:29146)
child (pid:29147)
prompt>

child 不会从 main() 重新开始;它仿佛自己调用了 fork()。child 拥有自己的 address space、registers 和 PC,但返回值不同:parent 得到 child PID,child 得到 0,失败时得到小于 0 的值。输出顺序由 CPU scheduler 决定,因此是不确定的。

程序开始时先打印一条包含 process identifier(PID)的 hello message。这个 process 的 PID 是 29146;在 UNIX system 中,如果想对 process 做某些事情(例如停止它),就使用 PID 来指代它。接着 process 调用 fork(),OS 由此创建一个新的 process。奇怪之处在于,新 process 几乎是 calling process 的 exact copy:对 OS 来说,现在看起来像有两个 p1 program 正在运行,并且两者都即将从 fork() 返回。新创建的 process,也就是 child,并不会像通常所想的那样从 main() 开始;它仿佛自己已经调用了 fork() 才来到这个世界,而前面的 hello 只被打印了一次。

child 并不是完全相同的 copy。它拥有自己的 address space(也就是自己的 private memory)、自己的 registers 和自己的 PC,但从 fork() 返回的 value 不同:parent 得到新 child 的 PID,child 得到 zero。这个差异让代码可以很容易地分别处理两种情况。

由于 child 创建后,system 中有两个 active processes,而单 CPU system 在任意时刻只能运行其中一个,因此 parent 或 child 都可能先运行。下面是另一种同样合法的输出顺序:

text
prompt> ./p1
hello (pid:29146)
child (pid:29147)
parent of 29147 (pid:29146)
prompt>

哪个 process 在某一时刻运行,由 CPU scheduler 决定。scheduler 很复杂,通常不能对它的选择作强假设,因此也不能假定哪个 process 一定先打印。这样的 non-determinism 会在 multithreaded programs 中带来许多有趣的问题;本书的 concurrency 部分会再次遇到更多 non-determinism。

5.2 The wait() System Call

parent 可用 wait()(或 waitpid())等待 child 完成:

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
    printf("hello (pid:%d)\n", (int) getpid());
    int rc = fork();
    if (rc < 0) { // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) { // child (new process)
        printf("child (pid:%d)\n", (int) getpid());
    } else { // parent goes down this path
        int rc_wait = wait(NULL);
        printf("parent of %d (rc_wait:%d) (pid:%d)\n",
               rc, rc_wait, (int) getpid());
    }
    return 0;
}

parent 调用 wait() 后 block;child 完成后 parent unblocked,wait() 返回。即使 parent 先运行,也会等待 child,因此 child 会先打印。

在这段程序中,parent 调用 wait() 来 block,也就是暂时延迟自己的 execution,直到 child 完成。child 完成后,parent 才会 unblocked,wait() 才会在 parent 中返回。因此加入 wait() 会让输出顺序变得 deterministic:如果 child 先运行,它会先打印;如果 parent 先运行,它会立即进入 wait(),而该调用在 child 运行并退出之前不会返回。无论哪种情况,parent 的最后一条 message 都会在 child 完成之后打印。

一个示例输出如下:

text
prompt> ./p2
hello (pid:29266)
child (pid:29267)
parent of 29267 (rc_wait:29267) (pid:29266)
prompt>

这里 wait() 的返回值是已经结束的 child 的 PID。wait() 在某些特殊情况下可能早于 child 退出而返回,具体行为应以对应 system 的 manual page 为准;不要把示例中的“总是”理解成脱离语境的绝对保证。

脚注:还要警惕本书中类似“child 总是先打印”或“UNIX 是世界上最好的东西,甚至比 ice cream 还好”这样的绝对、无条件表述。

5.3 Finally, The exec() System Call

若希望运行不同于 calling program 的 program,可在 child 中调用 exec():

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
    printf("hello (pid:%d)\n", (int) getpid());
    int rc = fork();
    if (rc < 0) { // fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) { // child (new process)
        printf("child (pid:%d)\n", (int) getpid());
        char *myargs[3];
        myargs[0] = strdup("wc"); // program: "wc"
        myargs[1] = strdup("p3.c"); // arg: input file
        myargs[2] = NULL; // mark end of array
        execvp(myargs[0], myargs); // runs word count
        printf("this shouldn’t print out");
    } else { // parent goes down this path
        int rc_wait = wait(NULL);
        printf("parent of %d (rc_wait:%d) (pid:%d)\n",
               rc, rc_wait, (int) getpid());
    }
    return 0;
}

exec() 从 executable 加载 code 和 static data,覆盖当前 process 的 program image,并重新初始化 heap、stack 等 memory。它不创建新 process,而是把当前 program 转换成另一个 program;成功的 exec() never returns,所以最后的 printf() 不会执行。

完整的 fork()、wait()、exec() 组合会得到如下行为:child 先打印自己的 message,然后调用 execvp() 运行 wc,让它统计 source file p3.c 的 lines、words 和 bytes;parent 等待 child 完成后再打印自己的 message。

text
prompt> ./p3
hello (pid:29383)
child (pid:29384)
29 107 1030 p3.c
parent of 29384 (rc_wait:29384) (pid:29383)
prompt>

在 Linux 上,exec() 有多个 variants,包括 execl()、execlp()、execle()、execv()、execvp() 和 execvpe();参数排列方式和是否通过 PATH 查找 executable 等细节不同,实际使用时应阅读相应的 man page。

5.4 Why: Motivating the API

shell 是 user program,通常执行以下流程:找到 executable,fork() 创建 child,child 调用 exec(),parent 调用 wait(),command 完成后再显示 prompt。

shell 之所以采用这样看似奇怪的接口,是因为 fork() 与 exec() 的分离,使 shell 能够在 fork() 之后、exec() 之前执行代码。这个短暂的窗口允许 shell 改变即将运行的 program 的 environment,从而很容易实现许多有用 features。

shell 本身只是一个 user program:它显示 prompt,等待用户输入 command(executable 的名字及其 arguments),找到 executable 在 file system 中的位置,调用 fork() 创建 child,在 child 中调用某个 exec() variant 运行 command,并在 parent 中调用 wait() 等待 command 完成。child 完成后,shell 从 wait() 返回,再次显示 prompt。

脚注:shell 有很多种,例如 tcsh、bash 和 zsh。应选择一种 shell,阅读它的 man pages 并进一步学习;所有 UNIX experts 都会这样做。

mermaid
sequenceDiagram
  participant S as Shell
  participant P as Parent
  participant C as Child
  S->>P: parse command
  P->>C: fork()
  C->>C: exec(program, args)
  P->>P: wait()
  C-->>P: exit
  P-->>S: next prompt

redirection 示例:

bash
prompt> wc p3.c > newfile.txt

shell 在 child 中、调用 exec() 前关闭 standard output,再打开 newfile.txt。open file descriptors 会跨越 exec() 保持打开,因此 wc 的 output 会进入 file。UNIX 从 descriptor 0 开始寻找空闲编号,所以关闭 standard output 后,新 file 可接收后续 standard-output writes。

UNIX pipes 使用 pipe():一个 process 的 output 连接到 kernel pipe,另一个 process 的 input 连接到同一个 pipe。例如 grep -o foo file | wc -l 可以查找并计数。

下面的 program 展示了 redirection 的完整做法:child 先关闭 STDOUT_FILENO,再打开 p4.output,然后执行 wc。parent 只负责 wait。

c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
    int rc = fork();
    if (rc < 0) { // fork failed
        fprintf(stderr, "fork failed\n");
        exit(1);
    } else if (rc == 0) { // child: redirect standard output to a file
        close(STDOUT_FILENO);
        open("./p4.output", O_CREAT|O_WRONLY|O_TRUNC,
             S_IRWXU);
        // now exec "wc"...
        char *myargs[3];
        myargs[0] = strdup("wc"); // program: wc
        myargs[1] = strdup("p4.c"); // arg: file to count
        myargs[2] = NULL; // mark end of array
        execvp(myargs[0], myargs); // runs word count
    } else { // parent goes down this path (main)
        int rc_wait = wait(NULL);
    }
    return 0;
}

运行它时,screen 上看不到 wc 的 output,因为 output 已经被重定向到 file:

text
prompt> ./p4
prompt> cat p4.output
32 109 846 p4.c
prompt>

redirection 能工作,是因为 UNIX 从 zero 开始寻找空闲 file descriptor。关闭 standard output 后,STDOUT_FILENO(通常是 descriptor 1)成为第一个可用 descriptor,接下来的 open() 就会得到它。child 后续通过 printf() 等 routine 写入 standard output 时,output 会透明地进入新打开的 file,而不是 screen。open file descriptors 会跨越 exec() 保持 open,这正是 shell 能实现 redirection 的关键。

运行 p4 时,表面上看似什么也没有发生:shell 立即再次显示 prompt;但实际上 p4 已经创建 child,并通过 execvp() 运行了 wc。只是 wc 的 output 被重定向到了 p4.output;随后用 cat 查看该 file,就能看到预期 output。

UNIX pipes 以类似方式实现,不过使用 pipe() system call:一个 process 的 output 连接到 kernel 中的 pipe(一个 queue),另一个 process 的 input 连接到同一个 pipe。这样,一个 command 的 output 就能无缝成为下一个 command 的 input,多个 commands 可以串成很长而有用的 chain。例如,grep -o foo file | wc -l 先查找 file 中的 foo,再统计匹配次数。

至此我们只是从 high level 勾勒了 process API。file descriptors 等内容还会在 persistence 部分继续展开;现在只需记住:fork() 与 exec() 的组合是创建和操作 processes 的一种 powerful 方式。

TIP:GETTING IT RIGHT(LAMPSON’S LAW)

“Get it right。Neither abstraction nor simplicity is a substitute for getting it right。”abstraction 和 simplicity 都不能替代 correctness;fork() 与 exec() 的组合简单而强大。

5.5 Process Control and Users

kill() 向 process 发送 signals。shell 中通常 Control-c 发送 SIGINT 并终止 process,Control-z 发送 SIGTSTP 并暂停 process,fg 可以恢复它。process 可以用 signal() catch signals,在收到 signal 时暂停 normal execution 并运行响应代码。

除了 fork()、exec() 和 wait(),UNIX 还提供许多与 processes 交互的 interfaces。kill() system call 用于向 process 发送 signals,包括 pause、die 等 directives。大多数 UNIX shells 会把特定的 keystroke combinations 配置为向当前运行的 process 发送特定 signal:Control-c 发送 SIGINT(通常会终止 process),Control-z 发送 SIGTSTP(暂停 process),稍后可以用 fg 这样的 shell built-in command 恢复它。

整个 signals subsystem 提供了向 processes 传递 external events 的 infrastructure。process 可以用 signal() system call “catch” 某个 signal;当该 signal 送达时,process 会暂停 normal execution,改为运行对应的 handler code。signals 既可以发送给单个 process,也可以发送给整个 process group;它们的完整语义较为丰富,具体细节应查阅相关文档。

现代多用户 system 通过 user、password 和 credentials 控制 process 权限。用户输入 password 建立 credentials 后登录 system,随后可以启动一个或多个 processes,并对自己的 processes 进行 pause、kill 等控制。通常 users 只能控制自己的 processes;OS 负责在 users 及其 processes 之间分配 CPU、memory 和 disk,以满足 system 的整体目标。

ASIDE:RTFM——READ THE MAN PAGES

man pages 是 UNIX system calls 和 library calls 的原始 documentation,而且早在 web 出现之前就已经存在。花时间阅读 man pages,是 systems programmer 成长的关键一步;尤其应阅读正在使用的 shell(如 tcsh 或 bash)以及 program 所调用的 system calls 的 man pages,以了解 return values 和 error conditions。当你向同事询问 fork() 的某个细节时,对方也许只会回答 “RTFM”;其中的 F 只是给 “Read The Man pages” 增添一点色彩。

5.6 Useful Tools

  • ps:查看正在运行的 processes;
  • top:查看 processes 及其 CPU、memory 消耗;它也会显示 system 当前消耗的其他 resources;
  • kill / killall:向 process 或一组 processes 发送 signals,使用时必须确认目标;
  • fg:恢复暂停的 foreground job。

还可以使用各种 CPU meters 快速观察 system load。macOS 上可以使用 MenuMeters 之类的工具,把 CPU utilization 显示在 menu bar 中。观察 process 和 system resource 的实际状态,是理解 process control 的一个很实用的补充。

top 还会显示 system 中 processes 正在消耗多少 CPU 和其他 resources;有趣的是,它经常声称自己才是最大的 resource hog,似乎有点 egomaniac。kill 和更 user-friendly 的 killall 都能发送 arbitrary signals,使用时务必小心;误杀 window manager 可能会让当前 computer 变得很难操作。

ASIDE:THE SUPERUSER(ROOT)

superuser(也叫 root)可以 kill 任意 process、执行 shutdown 等 powerful commands。拥有 root 权限有点像 Spider-Man:with great power comes great responsibility。为避免 costly mistakes,通常应使用 regular user;需要 root 时必须谨慎。

总结

目标调用组合结果
创建副本fork()得到 parent 和 child
等待 childwait()parent block 直到 child 完成
运行另一个 programfork() + exec()child 替换 program image
shell commandfork() + exec() + wait()创建、运行并回收 command
redirectionexec 前修改 descriptorsoutput 进入 file
pipelinepipe()一个 output 成为另一个 input

官方 Summary 与关键术语

本章只是介绍了 UNIX process-creation APIs 的表面;若要深入理解,应继续阅读 Stevens 和 Rago 关于 Process Control、Process Relationships 与 Signals 的章节。也要注意,fork() 并不是唯一可能的 process-creation 设计:有研究者认为 spawn() 等更简单的 APIs 可能更合适。即使是经典 UNIX API,也应把它看作一种设计选择,而不是唯一答案。

  • 每个 process 通常有一个数字名称,即 PID。
  • fork() 创建新 process;创建者是 parent,新 process 是 child,child 是 parent 的近似副本。
  • wait() 允许 parent 等待 child 完成。
  • exec() family 让 child 脱离与 parent 的相似性,执行全新的 program。
  • UNIX shell 常用 fork()、wait()、exec() 启动 commands;fork/exec 分离使 redirection、pipes 等 features 无需修改被运行的 programs。
  • signals 可以让 jobs stop、continue 或 terminate;user 概念决定某个人能控制哪些 processes,superuser 则能控制全部 processes。

本章 References

标记资料用途
[B+19]Andrew Baumann 等,《A fork() in the road》对 UNIX process API 的反对观点,主张更简单的 spawn() 等 process-creation API;HotOS ’19
[C63]Melvin E. Conway,《A Multiprocessor System Design》讨论 multiprocessing systems 的早期设计,可能是最早讨论以 fork() 创建 process 的论文之一
[DV66]Jack B. Dennis、Earl C. Van Horn,《Programming Semantics for Multiprogrammed Computations》早期 multiprogrammed computer systems 的经典论文
[J16]Phoebe Jackson-Edwards,《They could be twins!》与 parent/child 相似性相关的幽默引用
[L83]Butler Lampson,《Hints for Computer Systems Design》systems design 的经典建议,Get it right 的来源
[QI15]The Quote Investigator,《With Great Power Comes Great Responsibility》追溯“能力越大,责任越大”的引文来源
[SR05]W. Richard Stevens、Stephen A. Rago,《Advanced Programming in the UNIX Environment》UNIX APIs 的细节、Process Control、Process Relationships 与 Signals

Homework(Simulation)

官方 fork.py simulator 展示单个“family tree”中 processes 的关系。先阅读 README,再完成以下练习:

  1. 运行 ./fork.py -s 10,预测每一步的 process tree,并用 -c 检查;尝试不同 random seeds 和更多 actions(-a)。
  2. 改变 fork_percentage(-f),例如在 -a 100 下从 0.1 调到 0.9,预测最终 process trees 如何变化,并用 -c 验证。
  3. 使用 -t 切换 output;给定 process trees,判断可能采取了哪些 actions。
  4. 运行 ./fork.py -A a+b,b+c,c+d,c+e,c-,观察 c exit 后其 children 的去向;比较使用 -R 时的结果,并自行了解 orphaned processes。
  5. 使用 -F 跳过 intermediate steps,只根据生成的 actions 填出 final process tree;用不同 seeds 重复。
  6. 同时使用 -t 和 -F,根据 final tree 反推 actions;判断哪些情况下可以唯一确定,哪些情况下不能。

Homework(Code)

以下练习用于熟悉 process-management APIs:

  1. 在 fork() 前让 parent 修改 variable x(例如设为 100),观察 child 中的值,以及 parent/child 同时修改 x 时的结果。
  2. 使用 open() 打开 file 后再 fork();观察 parent 和 child 是否都能访问返回的 file descriptor,以及并发写入时发生什么。
  3. 创建 child 打印 hello、parent 打印 goodbye,尝试确保 child 总是先打印,但不在 parent 中调用 wait()。
  4. fork() 后使用某种 exec() 执行 /bin/ls,并在 Linux 上尝试 execl()、execle()、execlp()、execv()、execvp() 和 execvpe();思考为什么会有这么多 variants。
  5. 在 parent 中使用 wait() 等待 child,观察 wait() 返回什么;再尝试在 child 中调用 wait()。
  6. 用 waitpid() 替换 wait(),说明什么时候 waitpid() 更有用。
  7. 创建 child,关闭其 STDOUT_FILENO,再调用 printf();观察 output 会发生什么。
  8. 创建两个 children,用 pipe() 将一个 child 的 standard output 接到另一个 child 的 standard input。

与后续笔记的关系

参考资料

← 返回列表
← 上一篇 OSTEP:进程抽象 下一篇 → OSTEP:Limited Direct Execution

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论