linux - shell脚本执行成功后离开进程

标签 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

为什么脚本执行完了,这些进程还在?我应该对脚本进行哪些更改?

最佳答案

这主要是由于使用了 nohup 实用程序。使用该命令的问题是,每次从 start_Server() 函数调用调用它时,它都会 fork 一个新进程。

来自 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

关于linux - shell脚本执行成功后离开进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36646133/

相关文章:

linux - 删除 zip 存档中的文件 "older than"

linux - 检查视频文件是否有字幕

windows - 如何在cmd中调用嵌套程序

c - 为什么fork程序printf执行时间更长

Python Netsnmp 和 snmpwalk

linux - Shell 脚本在 Ubuntu 中没有给出预期的输出

linux - 在 Linux 上,如何仅通过 SSH 连接为 session 共享脚本?

xml - 从两个不同内容之间的 XML 文件中获取数据

linux - 在 Ubuntu 10.04(64 位机器)上访问物理内存时 PC 完全死机

linux - 在 Linux 中以交互方式打开和关闭输出?