我写了一个shell脚本,inturn使用nohup调用其他schell脚本。在脚本成功完成后,我仍然看到Linux进程正在为我编写的自定义脚本运行。
startAllComponents.sh 的内容
start_Server()
{
SERVER_HOME=${1}
NOHUP_LOG_FILE=${2}
logmsg "Starting the server"
/usr/bin/nohup `${SERVER_HOME}/bin/server.sh >> ${NOHUP_LOG_FILE} 2>&1 ` &
sleep 5
PID=`ps -ef|grep ${SERVER_HOME}/jvm |grep -v grep| awk '{print $2}'`
if [ "${PID}" = "" ]
then
logmsg "Couldn't get the PID after starting the server"
else
logmsg "****** Server started with PID: ${PID} ****** "
fi
}
logmsg()
{
echo "`date '+%b %e %T'` : $1"$'n' >> /tmp/STARTUP`date '+%Y%m%d'`_.log
}
#### Send an email #####
sendEmail()
{
RECIPIENTS="gut1kor@sample.com"
SMTP="1.1.1.1:25"
mailx -s "$SUBJECT" -S "smtp=smtp://$SMTP" $RECIPIENTS < /tmp/STARTUP`date '+%Y%m%d'`_.log
}
##### Main #####
INTS[0]="/opt/server/inst01;/home/gut1kor/nohup.inst01.out"
INTS[1]="/opt/server/inst02;/home/gut1kor/nohup.inst02.out"
INTS[2]="/opt/server/inst03;/home/gut1kor/nohup.inst03.out"
echo "##### Bringing up servers on `hostname`. #####"$'n' > /tmp/STARTUP`date '+%Y%m%d'`_.log
IS_TOTAL=${#INTS[@]}
logmsg "Total Servers are: ${IS_TOTAL}"
if [ "$IS_TOTAL" -gt "0" ]
then
for((i=0;i<IS_TOTAL;i++)) do
IFS=";" read -a arr <<< "${INTS[$i]}"
start_Server ${arr[0]} ${arr[1]}
done
fi
sendEmail
脚本在启动服务器实例时按预期工作,但在执行之后,我看到每个实例都有两个脚本进程在运行。
[gut1kor@HOST1 startAll]$ ps -ef|grep startAllComponents.sh
gut1kor 63699 1 0 18:44 pts/2 00:00:00 /bin/sh ./startAllComponents.sh
gut1kor 63700 63699 0 18:44 pts/2 00:00:00 /bin/sh ./startAllComponents.sh
gut1kor 63889 61027 0 18:45 pts/2 00:00:00 grep startAllComponents.sh
为什么在脚本执行完成之后,这些进程仍然存在?我应该对脚本进行哪些更改?
由于使用了nohup
实用程序,所以与此类似。使用该命令的问题是,每次从start_Server()函数调用它时,它都会分叉一个新进程。
从man
页面
nohup No Hang Up. Run a command immune to hangups, runs the given
command with hangup signals ignored, so that the command can
continue running in the background after you log out.
要终止nohup
启动的所有进程,您可能需要获取启动的命令的进程id,并在脚本结束时终止它。
/usr/bin/nohup $( ${SERVER_HOME}/bin/server.sh >> ${NOHUP_LOG_FILE} 2>&1 ) &
echo $! >> save_pid.txt # Add this line
在脚本的末尾。
sendEmail
while read p; do
kill -9 $p
done <save_pid.txt