Week 6 · Processes & System Interfaces
第 6 周 · 进程与系统接口
Creating, Coordinating & Communicating Between Processes
进程的创建、协调与通信
posix_spawn, exec, waitpid, pipes, and tracing process life-cycles to exam standards
从 posix_spawn、exec、waitpid 到管道通信,完整掌握进程全生命周期并贴合考试要求
🎯 Learning Objectives学习目标
-
Explain how the Linux scheduler manages processes, context switches, and preemption; map these behaviours to profiler output and exam tracing questions.
阐述 Linux 调度器如何管理进程、上下文切换与抢占,将这些行为映射到分析器输出与考试中的追踪题。
-
Create and manage child processes using
posix_spawn, exec*, and waitpid, documenting cleanup rules that align with Lab06 auto-tests.
使用 posix_spawn、exec* 与 waitpid 创建和管理子进程,并记录符合 Lab06 自动测试的清理规则。
-
Design robust pipe-based IPC patterns that avoid deadlocks, descriptor leaks, and race conditions; validate with unit tests and shell pipelines.
设计健壮的管道 IPC 模式,避免死锁、描述符泄露与竞态条件,并通过单元测试与 shell 管道验证。
-
Instrument process trees with
ps, strace, and logging hooks to justify behaviour in exam-style short answers.
使用 ps、strace 以及日志挂钩分析进程树,为考试简答题中的行为解释提供证据。
-
Summarise the security implications of
system() vs posix_spawn() and document safe wrappers for assignment-quality code.
总结 system() 与 posix_spawn() 的安全差异,为作业级代码编写安全封装。
🧭 Exam Alignment考试对齐
-
Process lifecycle tracing — 22T3 Q7 与 20T2 Q4 要求准确标注
fork/exec/wait 顺序与僵尸清理。
进程生命周期追踪 — 22T3 Q7 与 20T2 Q4 要求准确标注 fork/exec/wait 顺序与僵尸清理。
-
Shell pipeline reasoning — Lab06 «spawn_echo» 与 22T2 Q6 考察管道端关闭、防死锁策略。
管道推理 — Lab06 “spawn_echo” 与 22T2 Q6 聚焦管道端关闭以及防死锁策略。
-
Scheduler narratives — Tutorial06 讨论题映射到考试问答:解释抢占点、响应时间与上下文切换成本。
调度叙述 — Tutorial06 讨论题映射到考试问答:解释抢占点、响应时间与上下文切换成本。
-
Secure execution — 22T3 Q10 对
system() 与 posix_spawn() 的安全比较,Lab06 «spawn_read_pipe» 提供代码基础。
安全执行 — 22T3 Q10 比较 system() 与 posix_spawn() 的安全性,Lab06 “spawn_read_pipe” 提供代码骨架。
-
Signal handling — Tutorial07 预热题与过往 final(20T3 Q8)考查
SIGCHLD、忽略/拾取策略。
信号处理 — Tutorial07 预热题与 20T3 Q8 涉及 SIGCHLD 处理策略。
Target coverage: log ≥5 spawn/exec templates、≥3 pipe topologies (parent→child, child→parent, sibling relay) and ≥2 signal-cleanup recipes. Document gaps for Week 7 warm-up.
覆盖目标:记录 ≥5 个 spawn/exec 模板、≥3 种管道拓扑(父→子、子→父、兄弟中转)以及 ≥2 套信号清理方案,并标注需在第 7 周复习的薄弱点。
📚 Core Concepts核心概念
Schedulers & Context Switches调度器与上下文切换
Linux preempts tasks after a configurable time slice or when blocking on I/O. Save/restore CPU registers, stack pointer, and MMU state — costly operations that motivate minimising unnecessary switches.Linux 会在时间片耗尽或进程阻塞时抢占任务。上下文切换需保存/恢复寄存器、栈指针与 MMU 状态,代价高昂,因此应尽量减少不必要的切换。
Exam prompts often give ps/top snapshots — narrate why threads exhibit «S» (sleeping) vs «R» (running) and estimate wait-times.考试题常给出 ps/top 截图,要能解释线程为何处于 “S” (sleep) 或 “R” (running),并估计等待时间。
Process Creation APIs进程创建 API
posix_spawn() combines fork + exec with file-actions (dup2/close) to avoid double-running constructors. Use posix_spawn_file_actions_addclose/_adddup2 to configure pipes.posix_spawn() 将 fork 与 exec 合并,并允许通过 file-actions(dup2/close)配置文件描述符,避免重复执行构造函数。
execve() replaces the current image; all code after it runs only if the call fails — critical for safe exam answers.execve() 会替换当前进程映像;若调用成功,之后的代码不会执行,这点在考试解答中尤为重要。
Pipes & IPC Layouts管道与进程通信
Pipes are kernel-managed circular buffers (pipefd[0] read, pipefd[1] write). Close unused ends after fork/spawn, otherwise readers block forever.管道是由内核管理的环形缓冲区(pipefd[0] 读端、pipefd[1] 写端)。创建子进程后必须关闭未使用的端口,否则读端会一直阻塞。
Design patterns: parent→child streaming, child→parent reporting, teeing via two children for MapReduce-style tasks.常见模式:父进程向子进程推送数据、子进程向父进程回报结果、两个子进程通过管道实现 MapReduce 式分工。
Signals & Cleanup信号与清理
SIGCHLD notifies parents when children exit. Either ignore (auto reap) or install handler that loops waitpid(-1, ... , WNOHANG).SIGCHLD 在子进程退出时通知父进程。可选择忽略(由内核自动回收)或设置处理函数循环 waitpid(-1, ..., WNOHANG)。
Blocking signals is essential when manipulating shared structures (Lab06 «jobs» extension).在修改共享结构时阻塞信号至关重要(参见 Lab06 “jobs” 扩展题)。
🧪 Worked Examples例题串讲
Example 1 — Spawning a Filter Pipeline示例 1 — 构建过滤管道
Goal: run ls -1 | grep .c using posix_spawn twice and a pipe. Parent feeds stdout of ls into pipe, second child reads pipe and prints matches.目标:使用两次 posix_spawn 与一个管道实现 ls -1 | grep .c。父进程把 ls 的输出写入管道,第二个子进程从管道读取并输出匹配项。
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_adddup2(&actions, pipefd[1], STDOUT_FILENO);
posix_spawn_file_actions_addclose(&actions, pipefd[0]);
posix_spawn(&child_ls, "/bin/ls", NULL, &actions, argv_ls, environ);
posix_spawn_file_actions_destroy(&actions);
Always close pipe ends not needed in both parent and child. Forgetting leads to EOF never arriving in grading scripts.
父子进程都必须关闭未使用的管道端,否则自动测试会检测到读端无法收到 EOF。
Example 2 — Reaping Zombies with Signal Handler示例 2 — 用信号处理函数清理僵尸进程
Install handler: set SA_RESTART | SA_NOCLDSTOP, loop while (waitpid(-1, &status, WNOHANG) > 0). Record exit status for logging.安装信号处理函数:设置 SA_RESTART | SA_NOCLDSTOP,并循环 while (waitpid(-1, &status, WNOHANG) > 0),记录退出状态用于日志。
Exam link: 22T2 Q6 asks why ignoring SIGCHLD fixed zombie leak.考试关联:22T2 Q6 讨论为何忽略 SIGCHLD 能消除僵尸进程。
⚠️ Common Pitfalls易错点
- Leaving descriptors open in both parent and child causing dead reads. Solution: close immediately after
posix_spawn/fork.父子进程同时保留管道描述符导致读端阻塞;解决方案是在 posix_spawn/fork 后立即关闭。
- Using
system() with user input: shells interpret metacharacters; prefer posix_spawn with argument array.用 system() 直接传入用户输入会被 shell 解析元字符;应改用传参数组的 posix_spawn。
- Forgetting to reap children before exiting main — exam graders allocate penalties for zombie accumulation.主进程退出前未回收子进程会产生僵尸,考试按僵尸数量扣分。
- Calling async-unsafe functions inside signal handlers (e.g.
printf). Use write or set a flag.在信号处理函数内调用 printf 等异步不安全函数;应改用 write 或设置标志。
🛠️ Practice Task实践任务
Implement proc_mux.c: spawn three worker programs (./fetch, ./filter, ./format) communicating via pipes. Parent coordinates startup, forwards STDIN to first worker, and merges final output.实现 proc_mux.c:生成 ./fetch、./filter、./format 三个子进程,通过管道串联。父进程负责启动、将 STDIN 转给第一个子进程,并汇总最终输出。
- Log each
posix_spawn call with PID and command for debugging; required for Lab06 bonus tests.记录每次 posix_spawn 调用的 PID 与命令,便于调试,也是 Lab06 附加测试要求。
- Install SIGCHLD handler to reap early terminations; if any worker exits non-zero, cancel pipeline and report.安装 SIGCHLD 处理器回收提前退出的进程;若某 worker 返回非零,立即终止管道并报告。
- Optional Optional: expose
--profile flag to print scheduling timestamps gathered via clock_gettime.可选 Optional:实现 --profile 参数,使用 clock_gettime 输出调度时间点。
🧪 Tutorial & Lab Mapping教程与实验映射
Tutorial 06 HighlightsTutorial 06 精要
- Process tree tracing with
ps --forest; practise explaining parent/child lineage diagrams.使用 ps --forest 分析进程树,练习解释父子关系图。
- Scheduling debate: round-robin vs priority vs real-time scenarios — prepare short-form answers.调度讨论:轮询、优先级与实时场景,准备考试简答思路。
- Signal puzzles: why ignoring SIGCHLD stops zombie accumulation.信号题:解释为何忽略 SIGCHLD 能阻止僵尸进程。
Lab 06 Programming TasksLab 06 编程任务
- spawn_echo.c — spawn program, connect stdout via pipe, echo results; emphasises fd hygiene.spawn_echo.c — 生成程序并通过管道连接 stdout,重点关注描述符管理。
- spawn_filter.c — two-stage pipeline, practise closing ends and handling errors.spawn_filter.c — 实现双级管道,练习关闭端点与错误处理。
- spawn_env.c — modify environment before exec; exam often checks env sanitation.spawn_env.c — 在 exec 前调整环境变量;考试常问环境清理。
- jobs.c (challenge) — build mini job control using signals and waitpid.jobs.c(挑战) — 通过信号与 waitpid 构建迷你作业管理器。
📝 Study Log学习记录
-
Inputs shared: processes.pdf, Lab06 specification, Tutorial06 handout, exam 22T3 Q7 + 22T2 Q6 trace scripts.
提供给 AI 的资料: processes.pdf、Lab06 说明、Tutorial06 讲义、22T3 Q7 与 22T2 Q6 的追踪脚本。
-
Prompt: “Synthesise spawn/pipe templates aligned with Lab06 autograder & explain scheduler outputs.”
核心提示词:“整合符合 Lab06 自动评测的 spawn/pipe 模板,并解析调度输出。”
-
Breakthrough: Logging PID + command at spawn time made deadlock debugging trivial; adopted sticky template.
收获: 在生成时记录 PID 与命令极大简化了死锁调试,已固化为模板。
-
Misconception fixed: Previously tried to reuse
system() for pipelines — now replaced with posix_spawn wrapper.
修正误区: 过去使用 system() 连接管道,现改用 posix_spawn 封装。
-
Action items: Implement optional profiling flag; practise explaining context-switch cost for 3 scheduling snapshots.
后续行动: 开发可选的调度分析参数;练习解释三个调度截图的上下文切换代价。
Premium Quiz — 40 Process Mastery QuestionsPremium 测验 — 40 题掌握进程要点
28 basic (APIs & tracing) · 8 intermediate (pipeline tuning) · 4 advanced (signals & diagnostics)基础 28 题(API 与追踪)· 中级 8 题(管道调优)· 高级 4 题(信号与诊断)
🔒
Open Week 6 Quiz (Premium)
打开第 6 周测验(会员)
🔭 Next Week Preview下周预告
Week 7 explores concurrency and threads: mutexes, condition variables, deadlock avoidance, and atomic operations. Review threads.pdf and Lab07 «bank_account» before lecture.第 7 周将探讨并发与线程:互斥量、条件变量、死锁规避与原子操作。课前请预习 threads.pdf 与 Lab07 “bank_account”。
📎 Resources & Checklist资源与检查表
- PPT: processes.pdf p1–34 (context switches) & supporting code samples.PPT: processes.pdf 第 1–34 页(上下文切换)及示例代码。
- Autotest:
1521 autotest lab06_spawn_echo, lab06_spawn_filter, lab06_spawn_env, lab06_jobs.自动测试:1521 autotest lab06_spawn_echo、lab06_spawn_filter、lab06_spawn_env、lab06_jobs。
- Self-check: Can explain why ignoring SIGCHLD is safe? Can sketch fd table after spawning pipelines?自检: 能否解释忽略 SIGCHLD 的安全性?能否绘制生成管道后的文件描述符表?