2016-04-15 38 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