"""Offline Perl 5 semantic verification lab for Chapter 28 (process-management)."""
import json
import os
import subprocess
import sys
VERSION = "CPython 3.12.14 offline Perl 5 process-model verifier (perl absent)"
def case_pid_env_and_backtick_capture():
parent_pid = os.getpid()
child_env = dict(os.environ)
child_env["PERL_LAB_TAG"] = "mbsky-demo"
# Simulate backticks `...` capturing stdout lines cleanly via child python process
proc = subprocess.run(
[sys.executable, "-c", "import os; print(os.getpid()); print(os.environ['PERL_LAB_TAG'])"],
env=child_env,
capture_output=True,
encoding="utf-8",
timeout=15,
)
lines = proc.stdout.strip().splitlines()
child_pid = int(lines[0])
expected = {
"exit_code": 0,
"pid_positive": True,
"child_pid_distinct": True,
"env_inherited": "mbsky-demo",
"parent_env_unmodified": True,
}
actual = {
"exit_code": proc.returncode,
"pid_positive": parent_pid > 0,
"child_pid_distinct": child_pid != parent_pid,
"env_inherited": lines[1] if len(lines) > 1 else "",
"parent_env_unmodified": "PERL_LAB_TAG" not in os.environ,
}
return {
"name": "pid_env_and_backtick_capture",
"summary": "验证 $$ 进程号、%ENV 子进程环境变量继承隔离以及反引号风格标准输出捕获",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_system_quote_interpolation_and_list_safety():
perl_path_var = "我是 Perl 的变量"
shell_path_env = "/usr/local/bin:/bin:/usr/bin"
# Single-quoted 'echo $PATH' -> shell expands $PATH
single_q = shell_path_env
# Double-quoted "echo $PATH" -> Perl interpolates $PATH before invoking shell
double_q = perl_path_var
# Double-quoted with escape "echo \$PATH" -> shell sees $PATH and expands env
escaped_q = shell_path_env
# Multi-argument list form system($prog, @args) bypasses shell injection
payload = "hello; echo INJECTED"
proc = subprocess.run(
[sys.executable, "-c", "import sys; print(sys.argv[1])", payload],
capture_output=True,
encoding="utf-8",
timeout=15,
)
expected = {
"single_quote_result": "/usr/local/bin:/bin:/usr/bin",
"double_quote_result": "我是 Perl 的变量",
"escaped_dollar_result": "/usr/local/bin:/bin:/usr/bin",
"list_form_literal_arg": "hello; echo INJECTED",
"exit_status_shifted": 0,
}
actual = {
"single_quote_result": single_q,
"double_quote_result": double_q,
"escaped_dollar_result": escaped_q,
"list_form_literal_arg": proc.stdout.strip(),
"exit_status_shifted": (proc.returncode << 8) >> 8,
}
return {
"name": "system_quote_interpolation_and_list_safety",
"summary": "验证 system 单引号/双引号/反斜杠转义 $PATH 展开差异及列表形式防 Shell 注入",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_fork_exec_waitpid_and_sigchld_ignore():
def simulate_fork_wait(sig_chld: str, child_pid: int) -> dict:
# In parent: fork() returns child_pid (>0); in child: returns 0; on error: undef
if sig_chld == "IGNORE":
# Kernel auto-reaps exited child; waitpid returns -1 (no waitable child)
return {"parent_fork_ret": child_pid, "child_fork_ret": 0, "waitpid_ret": -1, "zombie_avoided": True}
return {"parent_fork_ret": child_pid, "child_fork_ret": 0, "waitpid_ret": child_pid, "zombie_avoided": True}
default_res = simulate_fork_wait("DEFAULT", 47117)
ignore_res = simulate_fork_wait("IGNORE", 47118)
expected = {
"default_waitpid": 47117,
"ignore_waitpid": -1,
"child_branch_zero": True,
"both_avoid_zombie": True,
}
actual = {
"default_waitpid": default_res["waitpid_ret"],
"ignore_waitpid": ignore_res["waitpid_ret"],
"child_branch_zero": default_res["child_fork_ret"] == 0 and ignore_res["child_fork_ret"] == 0,
"both_avoid_zombie": default_res["zombie_avoided"] and ignore_res["zombie_avoided"],
}
return {
"name": "fork_exec_waitpid_and_sigchld_ignore",
"summary": "验证 fork 返回值分流、waitpid 回收子进程 PID 以及 $SIG{CHLD}='IGNORE' 返回 -1 机制",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_kill_signal_table_and_validation():
linux_signals = {
"HUP": 1, "INT": 2, "QUIT": 3, "ILL": 4, "ABRT": 6,
"FPE": 8, "KILL": 9, "USR1": 10, "SEGV": 11, "USR2": 12,
"PIPE": 13, "ALRM": 14, "TERM": 15, "CHLD": 17, "CONT": 18,
"STOP": 19, "TSTP": 20, "TTIN": 21, "TTOU": 22,
}
# Simulate resolving kill('INT', 104, 102) without sending real signals
sig_name = "INT"
target_pids = [104, 102]
expected = {
"signal_count": 19,
"sigint_num": 2,
"sigkill_num": 9,
"sigterm_num": 15,
"sigchld_num": 17,
"resolved_call": {"signal": 2, "pids": [104, 102]},
}
actual = {
"signal_count": len(linux_signals),
"sigint_num": linux_signals["INT"],
"sigkill_num": linux_signals["KILL"],
"sigterm_num": linux_signals["TERM"],
"sigchld_num": linux_signals["CHLD"],
"resolved_call": {"signal": linux_signals[sig_name], "pids": target_pids},
}
return {
"name": "kill_signal_table_and_validation",
"summary": "核对 19 项常用 Linux 信号编号(含 INT=2/KILL=9/TERM=15/CHLD=17)与 kill 信号解析",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_pid_env_and_backtick_capture(),
case_system_quote_interpolation_and_list_safety(),
case_fork_exec_waitpid_and_sigchld_ignore(),
case_kill_signal_table_and_validation(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。
入口文件:projects/perl-process-management-lab/explore-process-management.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-process-management.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2480.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2498.zip