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

Shell script leaving process after successful execution

我写了一个 shell 脚本,它反过来使用 nohup 调用其他 schell 脚本。成功完成脚本后,我仍然看到我编写的自定义脚本 Linux 进程 运行。

startAllComponents.sh

的内容
start_Server()
{   
SERVER_HOME=
NOHUP_LOG_FILE=
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 }'`        
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'` : "$'\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