目录
正在加载目录…
正在阅读专栏 xv6 / MIT 6.1810:内核机制与可运行实现 第 1 篇 · 共 12 篇 · 8%

xv6:Operating system interfaces

发布于 2026-09-17 22:03 · 最后编辑于 2026-09-17 22:34 · 版本 v2 · 字数 16,088 · 预计阅读 33 分钟 👁 30 次阅读

xv6:Operating system interfaces

本文逐段翻译 xv6 book rev5 的 Foreword、Chapter 1;代码、API、图表和原文顺序保持不变,译文中的关键术语保留英文以便对照 source。

TL;DR

  • 操作系统的工作:在多个程序之间共享计算机,并提供硬件本身没有的更有用服务。
  • 核心接口:system call、process memory、file descriptor、pipe 和 file system 共同构成 Unix-like interface。
  • 关键组合:fork() 复制执行上下文,exec() 替换程序映像,file descriptor 让 shell 能组合 redirection 和 pipeline。
  • 边界:xv6 追求 simplicity 和 clarity,不是 POSIX-compliant 的现代生产 kernel。

名词解释

名词含义本文对应物
kernel为运行中程序提供服务的特殊程序xv6 kernel
process拥有 instructions、data、stack 和 kernel-private state 的运行单元shell、cat、wc
system calluser program 请求 kernel 服务的接口调用fork、exec、read、write
file descriptor表示 kernel-managed I/O object 的小整数0/1/2:standard input/output/error
inode文件本体及其 metadata被多个 directory entry 通过 link 指向

目录

章节说明
前言与致谢rev5 的材料定位与阅读方法
Chapter 1:Operating system interfaces操作系统接口总览
1.1 Processes and memoryfork、wait、exec、sbrk
1.2 I/O and File descriptorsdescriptor、offset、redirection
1.3 Pipespipe、EOF 和 pipeline
1.4 File systempath、directory、inode、link
1.5 Real worldPOSIX、Unix 与 xv6 的边界
1.6 Exercises原文练习

前言与致谢

这是一本面向操作系统课程的 draft text。它通过研究一个名为 xv6 的示例 kernel,解释操作系统的主要概念。xv6 以 Dennis Ritchie 和 Ken Thompson 的 Unix Version 6(v6)[17] 为模型。xv6 大体沿用 v6 的结构和风格,但使用 ANSI C [7] 实现,目标平台是 multi-core RISC-V [15]。

本书应当与 xv6 的 source code 一起阅读;这种方法受到 John Lions 的 Commentary on UNIX 6th Edition [11] 启发。书中的链接会指向 xv6 source code:https://github.com/mit-pdos/xv6-riscv。关于 v6 和 xv6 的在线资源,以及使用 xv6 的若干 lab assignment,可访问 https://pdos.csail.mit.edu/6.1810。

作者曾在 MIT 的操作系统课程 6.828 和 6.1810 中使用这份材料。感谢这些课程的 faculty、teaching assistants 和 students;他们都直接或间接地为 xv6 作出了贡献。特别感谢 Adam Belay、Austin Clements 和 Nickolai Zeldovich。也感谢通过邮件报告文本错误或提出改进建议的所有人。

如果你发现错误或有改进建议,请发送邮件给 Frans Kaashoek 和 Robert Morris(kaashoek,rtm@csail.mit.edu)。

Chapter 1:Operating system interfaces

操作系统的工作,是在多个程序之间共享一台计算机,并提供一组比单独使用硬件更加有用的服务。操作系统管理并抽象底层硬件;例如,word processor 不必关心正在使用哪一种 disk hardware。操作系统在多个程序之间共享硬件,使它们能够同时运行(或者看起来像是同时运行)。最后,操作系统以受控的方式让程序彼此交互,从而共享数据或协同工作。

操作系统通过 interface 向 user programs 提供服务。事实证明,设计一个好的 interface 很困难。一方面,我们希望 interface 简单而狭窄,因为这样更容易正确实现。另一方面,我们可能会想为 applications 提供许多 sophisticated features。解决这种张力的诀窍,是设计依赖少量 mechanisms 的 interfaces,再把这些 mechanisms 组合起来,提供很强的通用性。

本书使用一个具体的操作系统来说明操作系统概念。这个操作系统就是 xv6;它提供了 Ken Thompson 和 Dennis Ritchie 的 Unix 操作系统所引入的基本 interfaces [17],同时也仿照 Unix 的内部设计。

Unix 提供了一个狭窄的 interface,而其中的 mechanisms 可以良好组合,因而具有出人意料的通用性。这个 interface 如此成功,以至于现代操作系统——BSD、Linux、macOS、Solaris,甚至在较小程度上包括 Microsoft Windows——都具有 Unix-like interfaces。理解 xv6,是开始理解这些系统以及许多其他系统的好起点。

如图 1.1 所示,xv6 采用 kernel 的传统形式:kernel 是一个为运行中程序提供服务的特殊程序。每个运行中的程序称为 process,它拥有包含 instructions、data 和 stack 的 memory。instructions 实现程序的计算;data 是计算所作用的 variables;stack 组织程序的 procedure calls。一台给定的计算机通常有许多 processes,但只有一个 kernel。

当 process 需要调用 kernel 服务时,它会调用 system call,即操作系统 interface 中的某个 call。system call 进入 kernel;kernel 执行服务后返回。因此,一个 process 会在 user space 和 kernel space 之间交替执行。

正如后续章节会详细介绍的,kernel 使用 CPU 提供的 hardware protection mechanisms,确保每个在 user space 中执行的 process 只能访问自己的 memory。kernel 以实现这些保护所需的 hardware privileges 执行;user programs 则没有这些 privileges。当 user program 调用 system call 时,hardware 会提升 privilege level,并开始执行 kernel 中预先安排好的 function。

xv6 图 1.1

kernel 提供的 system calls 集合,就是 user programs 所看到的 interface。xv6 kernel 提供 Unix kernels 传统上提供的那组服务和 system calls 的一个子集。图 1.2 列出了 xv6 的全部 system calls。

System callDescription
int fork()Create a process, return child’s PID.
int exit(int status)Terminate the current process; status reported to wait(). No return.
int wait(int *status)Wait for a child to exit; exit status in *status; returns child PID.
int kill(int pid)Terminate process PID. Returns 0, or -1 for error.
int getpid()Return the current process’s PID.
int pause(int n)Pause for n clock ticks.
int exec(char *file, char *argv[])Load a file and execute it with arguments; only returns if error.
char *sbrk(int n)Grow process’s memory by n zero bytes. Returns start of new memory.
int open(char *file, int flags)Open a file; flags indicate read/write; returns an fd (file descriptor).
int write(int fd, char *buf, int n)Write n bytes from buf to file descriptor fd; returns n.
int read(int fd, char *buf, int n)Read n bytes into buf; returns number read; or 0 if end of file.
int close(int fd)Release open file fd.
int dup(int fd)Return a new file descriptor referring to the same file as fd.
int pipe(int p[])Create a pipe, put read/write file descriptors in p[0] and p[1].
int chdir(char *dir)Change the current directory.
int mkdir(char *dir)Create a new directory.
int mknod(char *file, int, int)Create a device file.
int fstat(int fd, struct stat *st)Place info about an open file into *st.
int link(char *file1, char *file2)Create another name (file2) for the file file1.
int unlink(char *file)Remove a file.

图 1.2: Xv6 system calls。除非另有说明,这些 calls 在没有 error 时返回 0,在发生 error 时返回 -1。

本章剩余部分概述 xv6 的 services——processes、memory、file descriptors、pipes 和 file system——并通过 code snippets 与讨论说明 shell(Unix 的 command-line user interface)如何使用它们。shell 对 system calls 的使用说明了这些 calls 是多么经过精心设计。

shell 是一个普通 program:它从 user 读取 commands 并执行它们。shell 是 user program 而不是 kernel 的一部分,这一事实体现了 system-call interface 的力量:shell 没有什么特殊之处。这也意味着 shell 很容易被替换;因此,现代 Unix systems 有各种各样的 shells,每个 shell 都有自己的 user interface 和 scripting features。xv6 shell 是 Unix Bourne shell 核心思想的一个简单实现。

xv6 shell 的实现位于源码 (7850)。这里的链接指向 https://github.com/mit-pdos/xv6-riscv 上相关的 xv6 source code;这个特定编号表示 xv6-src-booklet.pdf 中的 sheet 和 line number,方式与 Lions 的 Commentary on UNIX 6th Edition [11] 相同。一个好的做法是:先在自己喜欢的 development environment、GitHub 或 PDF viewer 中尝试独立阅读 source code,再回到本书。读完本书时,你应该能够在不查阅本书的情况下理解 xv6 source code 的每一行。

1.1 Processes and memory

一个 xv6 process 由 user-space memory(instructions、data 和 stack)以及属于 kernel、对每个 process 私有的 state 组成。xv6 会 time-share processes:它透明地在等待执行的 processes 集合之间切换可用的 CPUs。当 process 没有执行时,xv6 保存该 process 的 CPU registers;下次运行它时,再恢复这些 registers。kernel 为每个 process 关联一个 process identifier,即 PID。

process 可以使用 fork system call 创建一个新 process。fork 为新 process 创建 calling process memory 的精确副本:它把 calling process 的 instructions、data 和 stack 复制到新 process 的 memory 中。fork 会在原 process 和新 process 中都返回。在原 process 中,fork 返回新 process 的 PID;在新 process 中,fork 返回 zero。原 process 和新 process 通常分别称为 parent 和 child。

例如,考虑下面这段使用 C programming language [7] 编写的 program fragment:

c
int pid = fork();
if(pid > 0){
printf("parent: child=%d\n", pid);
pid = wait((int *) 0);
printf("child %d is done\n", pid);
} else if(pid == 0){
printf("child: exiting\n");
exit(0);
} else {
printf("fork error\n");
}

exit system call 会使 calling process 停止执行,并释放 memory、open files 等 resources。exit 接收一个 integer status argument;按照惯例,0 表示 success,1 表示 failure。wait system call 返回当前 process 某个已经 exited(或被 killed)的 child 的 PID,并将 child 的 exit status 复制到传给 wait 的 address 中;如果 caller 的 children 都还没有 exit,wait 就会等待其中一个。如果 caller 没有 children,wait 会立即返回 -1。如果 parent 不关心 child 的 exit status,可以向 wait 传入一个 0 address。

在上面的例子中,输出行

text
parent: child=1234
child: exiting

可能以任意顺序出现(甚至可能彼此交错),这取决于 parent 或 child 哪一个先执行到自己的 printf call。child exit 之后,parent 的 wait 返回,于是 parent 打印:

text
parent: child 1234 is done

虽然 child 一开始拥有 parent memory 的副本,但 parent 和 child 使用彼此独立的 memory 与 registers 执行:在一个 process 中修改 variable 不会影响另一个 process。例如,当 wait 的返回值被存入 parent process 的 pid 时,它不会改变 child process 中的 pid;child 中的 pid 仍然是 zero。

exec system call 会用从 file system 中某个 file 加载的新 memory image 替换 calling process 的 memory。这个 file 必须具有特定格式,用来说明 file 的哪一部分存放 instructions、哪一部分是 data、从哪条 instruction 开始执行等。xv6 使用 ELF format;Chapter 3 会更详细地讨论它。通常,这个 file 是由 program source code 编译得到的。exec 成功时不会返回 calling program;相反,从 file 加载的 instructions 会从 ELF header 中声明的 entry point 开始执行。

exec 接收两个 arguments:包含 executable 的 file 名称,以及一个 string arguments array。例如:

c
char *argv[3];
argv[0] = "echo";
argv[1] = "hello";
argv[2] = 0;
exec("/bin/echo", argv);
printf("exec error\n");

这段 fragment 会把 calling program 替换成一个运行 /bin/echo 的 instance,并传入 argument list echo hello。大多数 programs 会忽略 argument array 的第一个 element;按照惯例,它是 program 的名称。

xv6 shell 使用上面的 calls 代表 users 运行 programs。shell 的主结构很简单,见 main (8001)。主循环使用 getcmd 读取 user 输入的一行,然后调用 fork,创建 shell process 的副本。parent 调用 wait,child 则运行 command。例如,如果 user 在 shell 中输入 echo hello,那么 runcmd 会以 echo hello 作为 argument 被调用。runcmd (7903) 运行实际的 command;对于 echo hello,它会调用 exec (7927)。如果 exec 成功,child 就会执行 echo 中的 instructions,而不是继续执行 runcmd。某个时刻,echo 会调用 exit,这会使 main (8001) 中 parent 从 wait 返回。

你可能会疑惑:为什么不把 fork 和 exec 合并成一个 call?后面会看到,shell 利用二者的分离来实现 I/O redirection。为了避免创建 duplicate process 后又立即用 exec 替换它所造成的浪费,operating kernels 会使用 virtual memory techniques(例如 copy-on-write,见 Section 5)优化针对这一用法的 fork 实现。

xv6 会隐式分配大部分 user-space memory:fork 分配 child 拷贝 parent memory 所需的 memory,exec 分配容纳 executable file 所需的 memory。运行时需要更多 memory 的 process(也许是为了 malloc)可以调用 sbrk(n),将 data memory 增长 n 个 zero bytes;sbrk 返回新 memory 的位置。

1.2 I/O and File descriptors

file descriptor 是一个表示 kernel-managed object 的小 integer;process 可以从该 object 读取或向其写入。process 可以通过 open file、directory 或 device 获得 file descriptor,也可以通过创建 pipe 或复制已有 descriptor 获得。为简单起见,我们经常把 file descriptor 所指向的 object 称为“file”;file descriptor interface 抽象了 files、pipes 和 devices 之间的差异,把它们都表现为 byte streams。我们把 input 和 output 称为 I/O。

在内部,xv6 kernel 使用 file descriptor 作为 per-process table 的 index,因此每个 process 都有一组从 zero 开始的私有 file descriptors。按照惯例,process 从 file descriptor 0(standard input)读取,向 file descriptor 1(standard output)写 output,并向 file descriptor 2(standard error)写 error messages。后面会看到,shell 利用这一约定实现 I/O redirection 和 pipelines。shell 确保自己始终打开三个 file descriptors (8007);默认情况下,它们都是 console 的 file descriptors。

read 和 write system calls 通过 file descriptors 指定 open files,从中读取 bytes 或向其中写入 bytes。read(fd, buf, n) 从 file descriptor fd 中最多读取 n 个 bytes,将它们复制到 buf,并返回读取的 byte 数。每个指向 file 的 file descriptor 都有一个关联的 offset。read 从当前 file offset 读取 data,然后按读取的 byte 数推进 offset;下一次 read 会返回紧接在第一次返回内容之后的 bytes。没有更多 bytes 可读时,read 返回 zero,表示 end of file。

write(fd, buf, n) 从 buf 向 file descriptor 写入 n 个 bytes,并返回写入的 byte 数。只有发生 error 时,写入的才会少于 n 个 bytes。与 read 一样,write 从当前 file offset 写入 data,然后按写入的 byte 数推进 offset;每次 write 都从上一次停止的位置继续。

下面的 program fragment 构成了 cat program 的核心:它把 data 从 standard input 复制到 standard output;如果发生 error,就向 standard error 写入 message。

c
char buf[512];
int n;
for(;;){
n = read(0, buf, sizeof buf);
if(n == 0)
break;
if(n < 0){
fprintf(2, "read error\n");
exit(1);
}
if(write(1, buf, n) != n){
fprintf(2, "write error\n");
exit(1);
}
}

这段 code 中需要注意的是,cat 不知道自己是在从 file、console 还是 pipe 读取;同样,cat 也不知道自己是在向 console、file 还是其他对象打印。使用 file descriptors,以及约定 file descriptor 0 是 input、file descriptor 1 是 output,使得 cat 可以保持简单。

close system call 释放一个 file descriptor,使它可以被未来的 open、pipe 或 dup system call 重用。新分配的 file descriptor 总是当前 process 中编号最小的未使用 descriptor。

file descriptors 与 fork 的交互使 I/O redirection 很容易实现。fork 会连同 memory 一起复制 parent 的 file descriptor table,因此 child 起始时拥有与 parent 完全相同的 open files。exec system call 会替换 calling process 的 memory,但保留其 file table。这种行为让 shell 可以这样实现 I/O redirection:先 fork,再在 child 中关闭并重新打开选定的 file descriptors,最后调用 exec 运行新 program。下面是 shell 为 cat < input.txt 运行的简化 code:

c
char *argv[2];
argv[0] = "cat";
argv[1] = 0;
if(fork() == 0) {
close(0);
open("input.txt", O_RDONLY);
exec("cat", argv);
}

child 关闭 file descriptor 0 后,open 一定会使用该 descriptor 打开新的 input.txt:因为 0 是最小的可用 file descriptor。于是 cat 执行时,file descriptor 0(standard input)指向 input.txt。parent process 的 file descriptors 不会被这段 sequence 改变,因为它只修改 child 的 descriptors。

xv6 shell 的 I/O redirection code 正是以这种方式工作 (7931)。注意,此时 shell 已经 fork 出了 child shell,而 runcmd 将会调用 exec 加载新 program。

open 的第二个 argument 是一组以 bits 表示的 flags,用来控制 open 的行为。可能的 values 定义在 fcntl header (4000–4004) 中:O_RDONLY、O_WRONLY、O_RDWR、O_CREATE 和 O_TRUNC。它们分别指示 open 以 reading、writing 或 reading and writing 的方式打开 file,在 file 不存在时创建 file,以及把 file 截断为 zero length。

现在应该清楚为什么 fork 和 exec 分成两个 calls 很有帮助:在二者之间,shell 有机会重定向 child 的 I/O,而不干扰主 shell 的 I/O setup。也可以设想一个假想的组合 system call forkexec,但用这样的 call 实现 I/O redirection 似乎很 awkward:shell 可以在调用 forkexec 前修改自己的 I/O setup,然后撤销这些修改;或者 forkexec 可以通过 arguments 接收 I/O redirection instructions;或者(最不吸引人的方案)让每个像 cat 这样的 program 都学会自己做 I/O redirection。

虽然 fork 会复制 file descriptor table,但每一个底层 file offset 都会在 parent 和 child 之间共享。考虑下面的例子:

c
if(fork() == 0) {
write(1, "hello ", 6);
exit(0);
} else {
wait(0);
write(1, "world\n", 6);
}

这段 fragment 结束时,连接到 file descriptor 1 的 file 会包含 data hello world。由于 wait 的作用,parent 的 write 只会在 child 完成后执行,因此它会从 child 的 write 停止的位置继续。这种行为有助于 shell command sequence 产生顺序 output,例如 (echo hello; echo world) >output.txt。

dup system call 复制已有的 file descriptor,并返回一个指向同一个底层 I/O object 的新 descriptor。两个 descriptors 共享 offset,就像通过 fork 复制出的 descriptors 一样。下面是把 hello world 写入 file 的另一种方式:

c
fd = dup(1);
write(1, "hello ", 6);
write(fd, "world\n", 6);

如果两个 file descriptors 是由同一个原始 file descriptor 经过一系列 fork 和 dup calls 派生出来的,它们就共享 offset。否则,即使它们是通过对同一个 file 分别调用 open 得到的,也不共享 offset。dup 允许 shell 实现这样的 command:ls existing-file non-existing-file > tmp1 2>&1。2>&1 告诉 shell,为 command 提供一个 descriptor 2,它是 descriptor 1 的 duplicate。于是,existing file 的名称和 non-existing file 的 error message 都会出现在 tmp1 中。xv6 shell 不支持对 error file descriptor 做 I/O redirection,但现在你已经知道如何实现它。

file descriptors 是一种强大的 abstraction,因为它们隐藏了所连接对象的细节:向 file descriptor 1 写入的 process,可能是在写 file、console 这样的 device,或者 pipe。

1.3 Pipes

pipe 是一个暴露给 processes 的小型 kernel buffer,它以一对 file descriptors 的形式出现:一个用于 reading,一个用于 writing。向 pipe 一端写入 data,会使 data 可以从另一端读取。pipes 为 processes 提供了通信方式。

下面的示例运行 wc,并把它的 standard input 连接到 pipe 的 read end。

c
int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = 0;
pipe(p);
if(fork() == 0) {
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
exec("/bin/wc", argv);
} else {
close(p[0]);
write(p[1], "hello world\n", 12);
close(p[1]);
}

program 调用 pipe,创建一个新 pipe,并把 read、write file descriptors 记录到 array p 中。fork 之后,parent 和 child 都拥有指向该 pipe 的 file descriptors。child 调用 close 和 dup,使 file descriptor zero 指向 pipe 的 read end,然后关闭 p 中的 descriptors,并调用 exec 运行 wc。wc 从 standard input 读取时,实际就是从 pipe 读取。parent 关闭 pipe 的 read side,向 pipe 写入 data,然后关闭 write side。

如果没有 data 可用,pipe 上的 read 会等待,直到有 data 被写入,或者所有指向 write end 的 file descriptors 都被关闭;后一种情况下,read 会返回 0,就像 data file 到达 end 一样。read 会阻塞直到确定不可能再有新 data 到达;这也是 child 在执行上面的 wc 之前关闭 write end 很重要的原因:如果 wc 的某个 file descriptor 仍然指向 pipe 的 write end,wc 就永远看不到 end-of-file。

xv6 shell 以类似方式实现 grep fork sh.c | wc -l 这样的 pipelines (7950)。child process 创建一个 pipe,把 pipeline 左端连接到右端。然后它调用 fork 和 runcmd 运行左端,再调用 fork 和 runcmd 运行右端,并等待两者结束。pipeline 的右端也可以是一个自身包含 pipe 的 command(例如 a | b | c);这个 command 又会 fork 两个新的 child processes(一个运行 b,一个运行 c)。因此,shell 可能创建一棵 process tree。这棵 tree 的 leaves 是 commands,interior nodes 是等待左右 children 完成的 processes。

Pipes 看起来似乎不比 temporary files 更强:pipeline

text
echo hello world | wc

可以不用 pipes,而写成:

text
echo hello world >/tmp/xyz; wc </tmp/xyz

在这种情况下,pipes 至少有三个优点。第一,pipes 会自动清理自己;使用 file redirection 时,shell 必须小心地在完成后删除 /tmp/xyz。第二,pipes 可以传输任意长的 data streams,而 file redirection 需要 disk 上有足够的 free space 来保存所有 data。第三,pipes 允许 pipeline stages 并行执行,而 file 方案要求第一个 program 完成后第二个才能开始。

1.4 File system

xv6 file system 提供 data files(其中包含未解释的 byte arrays)和 directories(其中包含指向 data files 及其他 directories 的 named references)。directories 构成一棵 tree,从一个称为 root 的特殊 directory 开始。路径 /a/b/c 表示 root directory / 中的 directory a 里的 directory b 中名为 c 的 file 或 directory。不以 / 开头的 paths,会相对于 calling process 的 current directory 解析;current directory 可以通过 chdir system call 改变。假定涉及的 directories 都存在,下面两个 code fragments 打开的是同一个 file:

c
chdir("/a");
chdir("b");
open("c", O_RDONLY);
open("/a/b/c", O_RDONLY);

第一个 fragment 把 process 的 current directory 改为 /a/b;第二个既不引用也不改变 process 的 current directory。

创建新 files 和 directories 的 system calls 包括:mkdir 创建新 directory,带有 O_CREATE flag 的 open 创建新 data file,mknod 创建新 device file。下面的例子展示了全部三种操作:

c
mkdir("/dir");
fd = open("/dir/file", O_CREATE|O_WRONLY);
close(fd);
mknod("/console", 1, 1);

mknod 创建一个指向 device 的 special file。device file 关联 major 和 minor device numbers(mknod 的两个 arguments),它们唯一标识一个 kernel device。process 之后打开 device file 时,kernel 会把 read 和 write system calls 转交给 kernel device implementation,而不是交给 file system。

一个 file 的 name 与 file 本体是不同的;同一个底层 file 被称为 inode,可以拥有多个 names,称为 links。每个 link 都是 directory 中的一条 entry;entry 包含 file name 和对 inode 的 reference。inode 保存 file 的 metadata,包括 file 的 type(file、directory 或 device)、length、file content 在 disk 上的位置,以及指向 file 的 links 数量。

fstat system call 获取 file descriptor 所指向 inode 的信息。它把信息填入 stat.h (4050) 中定义的 struct stat:

c
#define T_DIR 1 // Directory
#define T_FILE 2 // File
#define T_DEVICE 3 // Device
struct stat {
int dev; // File system’s disk device
uint ino; // Inode number
short type; // Type of file
short nlink; // Number of links to file
uint64 size; // Size of file in bytes
};

link system call 创建一个新的 file-system name,使它指向与已有 file 相同的 inode。下面的 fragment 创建一个名为 a、又名为 b 的新 file:

c
open("a", O_CREATE|O_WRONLY);
link("a", "b");

从 a 读取或向 a 写入,与从 b 读取或向 b 写入相同。每个 inode 都由唯一的 inode number 标识。执行上面的 code sequence 后,可以检查 fstat 的结果来确定 a 和 b 是否指向同一份底层内容:二者都会返回相同的 inode number(ino),而 nlink count 会被设置为 2。

unlink system call 从 file system 中移除一个 name。只有当 file 的 link count 为 zero 且没有 file descriptors 指向它时,file 的 inode 和保存其内容的 disk space 才会被释放。因此,把

c
unlink("a");

加入上面的 code sequence 后,inode 和 file content 仍可通过 b 访问。此外,

c
fd = open("/tmp/xyz", O_CREATE|O_RDWR);
unlink("/tmp/xyz");

是一种惯用方式:创建一个没有 name 的 temporary inode;当 process 关闭 fd 或退出时,它会被清理。

Unix 提供了可以从 shell 调用的 file utilities,例如 mkdir、ln 和 rm。这种设计允许任何人通过添加新的 user-level programs 扩展 command-line interface。事后看来,这个方案似乎显而易见;但 Unix 同期设计的其他 systems 经常把这些 commands 构建进 shell(并把 shell 构建进 kernel)。

cd 是一个例外,它被构建进 shell (8021)。cd 必须改变 shell 自己的 current working directory。如果 cd 作为普通 command 运行,shell 就会 fork 一个 child process,由 child 运行 cd,而 cd 只会改变 child process 的 working directory;parent(也就是 shell)的 working directory 不会改变。

1.5 Real world

Unix 把“standard” file descriptors、pipes 和方便的 shell syntax 组合起来,对编写通用、可复用的 programs 是一次重大推进。这个想法催生了“software tools”文化,而这种文化对 Unix 的力量和流行负有很大责任;shell 也是第一个所谓的“scripting language”。Unix system-call interface 延续至今,存在于 BSD、Linux 和 macOS 等 systems 中。

Unix system-call interface 已通过 Portable Operating System Interface(POSIX)standard 实现标准化。xv6 不符合 POSIX:它缺少许多 system calls(包括 lseek 这样的基本 call),而且它提供的许多 system calls 也不同于 standard。xv6 的主要目标,是在提供简单 Unix-like system-call interface 的同时保持 simplicity 和 clarity。有人扩展了 xv6,加入一些 system calls 和一个简单的 C library,使它能够运行基本 Unix programs。然而,现代 kernels 提供的 system calls 和 kernel services 要多得多。例如,现代 kernels 支持 networking、windowing systems、user-level threads、许多 device 的 drivers 等等。现代 kernels 持续而快速地演化,提供的 features 远超 POSIX。

Unix 使用一组统一的 file-name 和 file-descriptor interfaces,统一访问多种 resource(files、directories 和 devices)。这个想法可以扩展到更多种类的 resources;Plan 9 [16] 就是一个很好的例子,它把“resources are files”这一概念应用到 networks、graphics 等领域。然而,大多数 Unix-derived operating systems 没有沿着这条路线发展。

file system 和 file descriptors 是强大的 abstractions。即便如此,操作系统 interface 仍有其他 models。Unix 的前身 Multics 把 file storage 抽象成看起来像 memory 的形式,产生了完全不同风格的 interface。Multics design 的复杂性直接影响了 Unix 的设计者;他们的目标是构建更简单的系统。

xv6 没有 users 的概念,也不提供将一个 user 与另一个 user 隔离保护的机制;用 Unix 的术语说,所有 xv6 processes 都以 root 身份运行。

本书考察 xv6 如何实现它的 Unix-like interface,但这些 ideas 和 concepts 并不只适用于 Unix。任何操作系统都必须把 processes multiplex 到底层 hardware 上,彼此隔离 processes,并提供受控的 inter-process communication mechanisms。学习 xv6 之后,你应该能够观察其他更复杂的 operating systems,并在这些 systems 中看到 xv6 背后的 concepts。

1.6 Exercises

  1. 编写一个 program,使用 UNIX system calls,让一个 byte 通过一对 processes 在两条 pipes 上来回传递;每个方向使用一条 pipe。测量这个 program 的 performance,单位是每秒完成的 exchanges。

图与格式复核

  • Figure 1.1:原文为 kernel、user space、kernel space、shell、cat 和 system call 的示意图;已在原文说明之后重建为同位置的 SVG,目标显示宽度 480px。
  • Figure 1.2:原文为 system-call table;已在对应段落之后保留为 Markdown table,API 签名和描述逐项对应 rev5。
  • 代码 listing:保留原始 C 代码、字符串、API 和注释;未把代码中的英文标识符翻译成中文。
  • 本章原文没有需要另存的照片类 raster image;示意图是可重建的 vector-style figure。

术语对照

English译法/处理
operating system操作系统
kernelkernel;必要处译作内核
processprocess;必要处译作进程
user space / kernel spaceuser space / kernel space
system callsystem call;必要处译作系统调用
file descriptorfile descriptor;必要处译作文件描述符
pipepipe;必要处译作管道
inodeinode
link / unlinklink / unlink
fork / exec保留 API 名称

参考资料

← 返回列表
← 返回专栏 xv6 / MIT 6.1810:内核机制与可运行实现 下一篇 → xv6:Operating system organization

评论 (0)

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