Issue
I wrote a shell script which inturn calls other schell scripts using nohup. After the successful completion of the script, I still see Linux process running for the custom script I wrote.
contents of 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="[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
The script works as expected in bringin up the server instances but after the execution I see two processes for the script running for each instance.
[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
Why these processes are still there even after the script execution is done? What changes should I make in the script?
Solution
It is mostly like due to the use of nohup
utility. The problem with the using the command is, it forks a new process every time it is invoked from start_Server() function call.
From the man
page
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.
To kill all the process started by nohup
you probably need to get the process id of the command started and kill it at the end of the script.
/usr/bin/nohup $( ${SERVER_HOME}/bin/server.sh >> ${NOHUP_LOG_FILE} 2>&1 ) &
echo $! >> save_pid.txt # Add this line
At the end of the script.
sendEmail
while read p; do
kill -9 $p
done <save_pid.txt
Answered By - Inian Answer Checked By - Mildred Charles (WPSolving Admin)