如何正确停止shell脚本?
问题描述:
我写了一个小的bash脚本,每3秒启动一个程序。这个脚本在启动时执行,并保存其PID为pidfile进程文件:如何正确停止shell脚本?
#!/bin/bash
echo $$ > /var/run/start_gps-read.pid
while [ true ] ; do
if [ "$1" == "stop" ] ;
then
echo "Stopping GPS read script ..."
sudo pkill -F /var/run/start_gps-read.pid
exit
fi
sudo /home/dh/gps_read.exe /dev/ttyACM0 /home/dh/gps_files/gpsMaus_1.xml
sleep 3
done
的问题是,我无法通过调用start_gps-read.sh stop
终止shell脚本。在那里它应该读取pidfile并停止初始化过程(从启动开始)。
但是当我打电话stop
,脚本仍然运行:
[email protected]_DataHarvest:~$ sudo /etc/init.d/start_gps-read.sh stop
Stopping GPS read script ...
[email protected]_DataHarvest:~$ ps aux | grep start
root 488 0.0 0.3 5080 2892 ? Ss 13:30 0:00 /bin/bash /etc/init.d/start_gps-read.sh start
dh 1125 0.0 0.2 4296 2016 pts/0 S+ 13:34 0:00 grep start
注:脚本总是为sudo
执行。
有谁知道如何停止我的shell脚本?
答
“停止”检查需要覆盖pid文件之前,并且肯定不需要在循环内。
if [ "$1" = stop ]; then
echo "Stopping ..."
sudo pkill -F /var/run/start_gps-read.pid
exit
fi
echo "$$" > /var/run/start_gps-read.pid
while true; do
sudo /home/dh/gps_read.exe ...
sleep 3
done
当您使用stop参数运行脚本时,它会覆盖您的PID文件。它试图自杀,而不是你以前想要杀死的过程。 – chepner