简体   繁体   中英

Stopping a running bash script from another script

I have a script called first.sh and this script calls another script using " ./second.sh ". In second.sh there are commands to play songs. For example, the content of second.sh could be:

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.

What can I do to stop second.sh using a command in the terminal? 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 .

Use crontab -e and append the below line

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

This kills the parent shell that invoked play

The syntax for the crontab file is

m h  dom mon dow   command

where:

m - minute
h - hours
dom - day of month
mon - month
dow - day of week
command - the command that you wish to execute.

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.

Requirement

You need to have the cron daemon up and running on your system.

You can save the pgid of the process explicitly, and then use the signals SIGSTOP and SIGCONT to start and stop the process group.

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 $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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