开发者

Shell-Scripting (BASH): What is the best way to toggle a script "on/off" that isn't able to end itself?

开发者 https://www.devze.com 2023-01-11 04:35 出处:网络
I would like to have a script with an infinite loop, that kills all processes created by this script when it gets executed again.

I would like to have a script with an infinite loop, that kills all processes created by this script when it gets executed again.

So basically you start the script via terminal:

bash poll.sh

and it's running infinitely, you open another terminal and again

bash poll.sh

and all poll.sh processes will get killed.

What would be the best way to do that? My first thought was to set environment variabl开发者_如何学Goes, something like export POLLRUNNING=true and poll.sh would implement something like if [ $POLLRUNNING = true ]; exit 1

My second idea was to work with touch .isrunning and statement to ask for that file.

How would you do that?


pidof(8) supports an -x flag to specify scripts; it also supports an -o omitpid flag to leave out specific pids. So:

#!/bin/bash

PIDS=`pidof -o $$ -x poll.sh`

if [ x$PIDS != x ]
    then kill -s SIGTERM $PIDS
fi

sleep 10
0

精彩评论

暂无评论...
验证码 换一张
取 消