daemon函数
daemon函数用于启动一个程序,并根据结果输出success或failure。
定义语句如下:
# A function to start a program.
daemon() {
# Test syntax.
local gotbase= force= nicelevel corelimit # 定义一大堆变量
local pid base= user= nice= bg= pid_file=
local cgroup=
nicelevel=0
while [ "$1" != "${1##[-+]}" ]; do # 当参数$1以"-"或"+"开头时进入循环,但$1为空时也满足
case $1 in
'') echo $"$0: Usage: daemon [+/-nicelevel] {program}" "[arg1]..."
return 1;;
--check) # daemon接受"--arg value"和"--arg=value"两种格式的参数
base=$2
gotbase="yes"
shift 2
;;
--check=?*)
base=${1#--check=}
gotbase="yes"
shift
;;
--user)
user=$2
shift 2
;;
--user=?*)
user=${1#--user=}
shift
;;
--pidfile)
pid_file=$2
shift 2
;;
--pidfile=?*)
pid_file=${1#--pidfile=}
shift
;;
--force)
force="force"
shift
;;
[-+][0-9]*)
nice="nice -n $1"
shift
;;
*) echo $"$0: Usage: daemon [+/-nicelevel] {program}" "[arg1]..."
return 1;;
esac
done
# Save basename.
[ -z "$gotbase" ] && base=${1##*/} # 若未传递"--check",则此处获取bashname
# See if it's already running. Look *only* at the pid file.
__pids_var_run "$base" "$pid_file"
[ -n "$pid" -a -z "$force" ] && return # 如进程已在运行(已检测出pid),且没有使用force
# 强制启动,则退出daemon函数
# make sure it doesn't core dump anywhere unless requested
corelimit="ulimit -S -c ${DAEMON_COREFILE_LIMIT:-0}" # corelimit、cgroup和资源控制有关,忽略它
# if they set NICELEVEL in /etc/sysconfig/foo, honor it
[ -n "${NICELEVEL:-}" ] && nice="nice -n $NICELEVEL"
# if they set CGROUP_DAEMON in /etc/sysconfig/foo, honor it
if [ -n "${CGROUP_DAEMON}" ]; then
if [ ! -x /bin/cgexec ]; then
echo -n "Cgroups not installed"; warning
echo
else
cgroup="/bin/cgexec";
for i in $CGROUP_DAEMON; do
cgroup="$cgroup -g $i";
done
fi
fi
# Echo daemon
[ "${BOOTUP:-}" = "verbose" -a -z "${LSB:-}" ] && echo -n " $base"
# And start it up. # 启动程序。runuser的"-s"指定执行程序的shell,$user指定运行的身份
# "$*"是剔除掉daemon选项后程序的启动指令。
if [ -z "$user" ]; then
$cgroup $nice /bin/bash -c "$corelimit >/dev/null 2>&1 ; $*"
else
$cgroup $nice runuser -s /bin/bash $user -c "$corelimit >/dev/null 2>&1 ; $*"
fi
[ "$?" -eq 0 ] && success $"$base startup" || failure $"$base startup"
}
daemon函数调用方法:
daemon [--check=servicename] [--user=USER] [--pidfile=PIDFILE] [--force] program [prog_args]
需要注意的是:
只有--user可以用来控制program启动的环境。
--check和--pidfile都是用来检查是否已运行的,不是用来启动的,如果提供了--check,则检查的是名为servicename的进程,否则检查的是program名称的进程。
--force则表示进程已存在时仍启动。
prog_args是向program传递它的运行参数,一般会从/etc/sysconfig/$base文件中获取。
例如httpd的启动脚本中。
echo -n $"Starting $prog: "
daemon --pidfile=${pidfile} $httpd $OPTIONS
这样的语句的执行结果大致如下:
[root@xuexi ~]# service httpd start
Starting httpd: [ OK ]
还需注意,通常program的运行参数可能也是--开头的,要和program前面的选项区分。例如:
daemon --pidfile $pidfile --check $servicename $processname --pid-file=$pidfile
第二个--pid-file是$processname的运行参数,第一个--pidfile是daemon检测$processname是否已运行的选项。由于提供了--check $servicename,所以函数调用语句__pids_var_run $base [pidfile]中的$base等于$servicename,即表示检查$servicename进程是否允许。如果没有提供该选项,则检查的是$processname。
至此,daemon函数已经分析完成。实际上很简单,就是为daemon提供几个选项,再提供要执行的命令,并为该命令提供启动参数。
|