Shell脚本在成功执行后离开进程

时间:2016-04-15 11:38:36

标签: linux bash shell scripting nohup

我写了一个shell脚本,它使用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

为什么即使在脚本执行完成后这些进程仍然存在?我应该在脚本中做出哪些更改?

1 个答案:

答案 0 :(得分:1)

这主要是因为使用了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