Back to COMP1521 Overview 返回 COMP1521 总览
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学习目标

🧭 Exam Alignment考试对齐

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易错点

🛠️ 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 转给第一个子进程,并汇总最终输出。

🧪 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学习记录

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资源与检查表