为了将服务器进程置于后台,直到服务器准备好为请求提供服务,您可以有一个在前台启动的脚本,执行设置和/或用户交互,然后当它准备好时,它可以在后台启动一个具有访问权限的子脚本到父级导出的变量和函数,然后退出。或者它可以在后台启动一个子shell,可以访问所有父变量和函数。
下面是 subshell 版本的简单演示脚本:
#!/bin/bash
reps=6 # vars in the parent are available in the subshell
var=123
f() { echo "$@"; } # a function in the parent is available in the subshell
f "starting"
# this read represents a startup delay for setup, etc., and/or user interaction
read -p "continue now? "
( # start the subshell
for ((i=1; i<=reps; i++))
do
f "$var" > "/tmp/bg.$$.$i"
# $$ will be meaningless when the parent script exits
# because, though it will have the value of the PID of the parent script
# the parent script will have exited leaving PID=1 (init) as the PPID of the subshell
# However $BASHPID will be the PID of the backgrounded subshell
sleep 10 # busy work
done
) & # put it in the background
f "process running in background"
f "ending parent"
顺便说一句,如果子shell 没有被发送到后台,它对其环境的更改将不会对其父级可用(无论如何,在上面的演示中也是如此)。