2016-04-15 40 views
2

我写了一个shell脚本,它使用nohup调用其他schell脚本。脚本成功完成后,我仍然看到Linux进程正在运行我写的自定义脚本。 startAllComponents.shShell脚本在成功执行后离开进程

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="[email protected]" 
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 

内容脚本按预期BRINGIN了服务器实例,但执行后,我看到两个进程为每个实例上运行的脚本。


[[email protected] 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 

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

+0

最初如何运行顶层脚本? –

+0

“nohup即使在用户注销后仍然保持命令运行,该命令将作为前台进程运行,除非后跟&。如果在脚本中使用nohup,请考虑将其与等待,以避免创建孤立进程或僵尸进程。 – jgr208

回答

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 
+0

你不觉得nohup线看起来怀疑这些反引号吗?那肯定没有做OP的想法,除非我错过了一些微妙的诀窍。 – richq

+0

@Etan Reisner我正在手动运行脚本(./startAllComponents.sh) – gut1kor

+0

@Inian感谢您的详细解释。是的,每次nohup被调用时,它都为脚本startAllComponents.sh创建2个父进程,为nohup命令本身创建2个父进程。我观察到,如果我按照您的建议手动杀死了nohup命令的PID,则脚本的父进程将被清除。我将在脚本中测试建议的更改并发布结果。谢谢。 – gut1kor