> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/4.3-bsd-unix-cao-zuo-xi-tong-she-ji-yu-shi-xian/di-er-bu-fen-jin-cheng/5.8.-wen-jian-de-zhi-xing.md).

# 5.8 文件的执行

`execve` 系统调用已在 2.4 节和 3.6 节描述过：它用取自可执行文件的新程序内容替换进程的地址空间。`exec` 期间，先验证目标可执行映像，再把参数和环境从当前进程映像复制到一块临时区域。

执行 `exec` 时，系统必须为虚拟地址的新内容分配资源，建立这一地址空间到新映像的映射，并释放现有虚拟内存使用的资源。这个过程之所以复杂，是因为资源（如系统页表）紧张时进程可能被换到辅存。

第一步是为新的数据和栈节分配交换空间。`exec()` 做这一分配时不先释放当前已分配的空间，因为系统必须始终在辅存上有地方可供换出进程（见 5.13 节）。若先释放当前交换空间而新的分配失败，`exec` 就无法回到原进程。这样分配出的重复交换空间记入进程 user 结构的影子交换映射；随后，当前进程的地址空间和虚拟内存资源被释放，就像进程正在退出一样；这一机制稍后描述。

此刻，进程只剩一个 user 结构和内核栈，外加只映射 user 结构的页表。保存新交换区的影子交换映射移到它们的正常位置，再为进程新的正文、数据、栈大小安排资源。安排的办法是把页表扩展到新尺寸并更新硬件寄存器。栈段的 PTE 设为零填充；若即将执行的映像不按需装载（少见的情况），则把已初始化数据读入数据空间，读取过程中按需调入所需页。

内核通过以下方式建立新地址空间的正文部分：若正文文件已在内存中，找到它的正文结构；否则分配并初始化一个新的正文结构。建立新正文结构时，为正文段和正文页表的交换映像分配交换空间。否则，把进程加入共享该正文的进程链表。正文页表按三种方式之一初始化：

1. 若内存中有别的进程在用这份正文，正文区的页表直接从那个进程复制。
2. 否则，若正文的页表副本在交换空间上，把交换副本读入相应位置。
3. 两条捷径都走不通时，页表按从文件填充建立。

第三种情形体现文件系统与虚拟内存系统信息重叠最大：正文 PTE 用每页簇的磁盘块号初始化。对每个被映射的文件系统块，必须用 `bmap()` 找到磁盘块号，并记入映射该块的各页簇的块号。这一映射操作代价高昂，因为 `bmap()` 可能要读过若干间接块才能找到某些文件系统块的位置。因此一次性做完所有映射更高效，使间接块在操作期间留在缓冲区高速缓存中。（文件系统运作的更多细节见第 7 章。）正文结构和页表初始化之后，已初始化数据的页表设为从文件填充。

`exec` 系统调用期间，建立新地址空间无须再做别的操作；余下的工作是把参数和环境复制到新栈的顶端。寄存器设好初值：程序计数器设为入口点，栈指针指向参数向量。新进程映像至此就绪，可以运行。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://book.bsdcn.org/4.3-bsd-unix-cao-zuo-xi-tong-she-ji-yu-shi-xian/di-er-bu-fen-jin-cheng/5.8.-wen-jian-de-zhi-xing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
