【问题标题】:How to stop a shell script correctly?如何正确停止 shell 脚本?
【发布时间】:2023-03-20 15:25:01
【问题描述】:

我编写了一个小 bash 脚本,每 3 秒启动一个程序。该脚本在启动时执行,并将其 PID 保存到 pidfile 中:

#!/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时,脚本仍然运行:

dh@Raspi_DataHarvest:~$ sudo /etc/init.d/start_gps-read.sh stop
Stopping GPS read script ...

dh@Raspi_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 脚本吗?

【问题讨论】:

  • 当您使用 stop 参数运行脚本时,它会覆盖您的 PID 文件。它试图杀死自己,而不是你试图杀死的前一个进程。

标签: linux bash shell debian


【解决方案1】:

“停止”检查需要在覆盖 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多