简体   繁体   English

从另一个脚本停止正在运行的bash脚本

[英]Stopping a running bash script from another script

I have a script called first.sh and this script calls another script using " ./second.sh ". 我有一个名为first.sh的脚本,该脚本使用“ ./second.sh ”调用另一个脚本。 In second.sh there are commands to play songs. second.sh中,有播放歌曲的命令。 For example, the content of second.sh could be: 例如, second.sh的内容可能是:

play song1.mp3
play song2.mp3
...

I want to stop the script second.sh at certain times during the day, the problem is that using killall (and similar commands) do not help because the name of the script " second.sh " does not appear among the list of commands when I use " ps aux ", I only see " play song1.mp3 " and then " play song2.mp3 " once song2 starts playing. 我想在一天中的某些时候停止脚本second.sh ,问题是使用killall (和类似的命令)无济于事,因为脚本“ second.sh ”的名称在以下情况下不会出现在命令列表中我使用“ 的ps aux”,我只看到“ 玩song1.mp3”,然后“ 玩song2.mp3”一旦song2开始播放。

What can I do to stop second.sh using a command in the terminal? 如何在终端中使用命令停止second.sh Or at least tie all the commands in it to a single process so I can kill that particular process? 或者至少将其中的所有命令绑定到单个进程,以便我可以杀死该特定进程?

Any help is appreciated, I've tried many ideas I found online but nothing seems to work. 感谢您的帮助,我已经尝试了很多在线发现的想法,但似乎没有任何效果。

Because you said : 因为你说:

at certain times during the day, 在一天中的某些时间,

I would recommend crontab . 我会推荐crontab

Use crontab -e and append the below line 使用crontab -e并添加以下行

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

This kills the parent shell that invoked play 这会杀死调用play的父外壳

The syntax for the crontab file is crontab文件的语法是

m h  dom mon dow   command

where: 哪里:

m - minute 米-分钟
h - hours 小时-小时
dom - day of month dom-每月的一天
mon - month 每月
dow - day of week 陶氏-星期几
command - the command that you wish to execute. command-您希望执行的命令。

Edit 编辑

Or you could do something like this : 或者,您可以执行以下操作:

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

which will pause all the play processes from 12 hours till 16 hours. 它将暂停从12小时到16小时的所有play过程。

Requirement 需求

You need to have the cron daemon up and running on your system. 您需要在系统上启动并运行cron守护程序。

You can save the pgid of the process explicitly, and then use the signals SIGSTOP and SIGCONT to start and stop the process group. 您可以显式保存进程的pgid,然后使用信号SIGSTOP和SIGCONT启动和停止进程组。

first.sh first.sh

#!/bin/bash

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

second.sh second.sh

#!/bin/bash

play ...
play ...

third.sh third.sh

#!/bin/bash

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

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

Now you can launch and control the play as follows: 现在,您可以按以下方式启动和控制播放:

./first.sh

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

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

killall second.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM