从另一个脚本停止 运行 bash 脚本

Stopping a running bash script from another script

我有一个名为 first.sh 的脚本,该脚本使用“./second.sh 调用另一个脚本”。在second.sh中有播放歌曲的命令。例如second.sh的内容可以是:

play song1.mp3
play song2.mp3
...

我想在白天的特定时间停止脚本 second.sh,问题是使用 killall (和类似的命令)没有帮助,因为当我使用“[=50”时,脚本“second.sh”的名称没有出现在命令列表中=] aux”,我只看到“play song1.mp3”,然后在 song2 开始后看到“play song2.mp3”正在播放。

如何在终端中使用命令停止 second.sh?或者至少将其中的所有命令绑定到一个进程,以便我可以终止该特定进程?

感谢任何帮助,我尝试了很多在网上找到的想法,但似乎没有任何效果。

因为你说:

at certain times during the day,

我会推荐 crontab

使用 crontab -e 并附加以下行

0 12 * * * kill -9 `ps aux | awk '/play/{print }'`

这会杀死调用 play

的父 shell

crontab 文件的语法是

m h  dom mon dow   command

其中:

米 - 分钟
h - 小时
dom - 月中的第几天
周一 - 月
dow - 星期几
命令 - 您希望执行的命令。

编辑

或者您可以这样做:

0 12 * * * killall -sSIGSTOP play
0 16 * * * killall -sSIGCONT play

这将暂停所有 play 进程 12 小时到 16 小时。

要求

您需要在系统上启动 cron 守护程序和 运行。

可以显式保存进程的pgid,然后使用信号SIGSTOP和SIGCONT来启动和停止进程组。

first.sh

#!/bin/bash

nohup ./second.sh > /dev/null 2>&1 &
echo $$ > /tmp/play.pid ### save process group id

second.sh

#!/bin/bash

play ...
play ...

third.sh

#!/bin/bash

case  in
    (start)
        kill -CONT -$(cat /tmp/play.pid)
        ;;

    (stop)
        kill -STOP -$(cat /tmp/play.pid)
        ;;
esac

现在您可以按如下方式启动和控制播放:

./first.sh

./third.sh stop
./third.sh start

您只需要停止 second.sh 它会自动杀死所有子进程。

killall second.sh