利用我们关于管理命令的知识,让我们来检查一个系统脚本。 最短和最容易理解的脚本之一是 "killall", [1],用于在系统关闭时暂停运行的进程。
示例 17-12. killall,来自/etc/rc.d/init.d
#!/bin/sh
# --> Comments added by the author of this document marked by "# -->".
# --> This is part of the 'rc' script package
# --> by Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>.
# --> This particular script seems to be Red Hat / FC specific
# --> (may not be present in other distributions).
# Bring down all unneeded services that are still running
#+ (there shouldn't be any, so this is just a sanity check)
for i in /var/lock/subsys/*; do
# --> Standard for/in loop, but since "do" is on same line,
# --> it is necessary to add ";".
# Check if the script is there.
[ ! -f $i ] && continue
# --> This is a clever use of an "and list", equivalent to:
# --> if [ ! -f "$i" ]; then continue
# Get the subsystem name.
subsys=${i#/var/lock/subsys/}
# --> Match variable name, which, in this case, is the file name.
# --> This is the exact equivalent of subsys=`basename $i`.
# --> It gets it from the lock file name
# -->+ (if there is a lock file,
# -->+ that's proof the process has been running).
# --> See the "lockfile" entry, above.
# Bring the subsystem down.
if [ -f /etc/rc.d/init.d/$subsys.init ]; then
/etc/rc.d/init.d/$subsys.init stop
else
/etc/rc.d/init.d/$subsys stop
# --> Suspend running jobs and daemons.
# --> Note that "stop" is a positional parameter,
# -->+ not a shell builtin.
fi
done |
这还不错。 除了使用变量匹配的一些花哨技巧之外,这里没有新的内容。
练习 1. 在/etc/rc.d/init.d中,分析 halt 脚本。它比 killall 脚本稍长,但在概念上类似。 将此脚本的副本复制到您主目录中的某个位置并进行实验(不要以 root 身份运行它)。 使用-vn标志进行模拟运行 (sh -vn scriptname)。 添加大量的注释。 将命令更改为 echos。
练习 2. 查看/etc/rc.d/init.d中一些更复杂的脚本。 尝试理解至少其中的一部分。 按照上述步骤分析它们。 为了获得更多见解,您还可以查看文件sysvinitfiles在/usr/share/doc/initscripts-?.??中,它是 "initscripts" 文档的一部分。
| [1] | 不应将 killall 系统脚本与 killall 命令混淆,后者位于/usr/bin. |