简体   繁体   中英

Terminating a shell script bar from a script foo

I have a script foo which, if provided an argument start , starts, among other things a script bar in the background and exits - bar contains an infinite loop.

At a later stage, I want to call foo with argument stop and I would like that script bar , which still runs in the background stops running.

What is the text book way of achieving this?

In case multiple bar instances can run simultaneously, and foo stop should stop/kill them all, use pkill :

$ pkill bar

to kill all processes named bar .

In case only one bar instance is allowed to run, a solution with a "pidfile" would be viable.

In foo :

pidfile=/var/run/bar.pid

if ((start)); then
    if [ -e "$pidfile" ]; then
        echo "$pidfile exists."
        # clean-up, or simply abort...
        exit 1
    fi
    bar &
    echo $! >"$pidfile"
fi

if ((stop)); then
    if [ ! -e "$pidfile" ]; then
        echo "$pidfile not found."
        exit 1
    fi
    kill "$(<"$pidfile")"
    rm -f "$pidfile"
fi

There are better ways to do what you're trying to do I believe if your host has systemd or initd there are frameworks already in place to have long running jobs with start/stop capabilities.

If you must do this independent of those or other useful tools I would solve it like this:

When you call foo start store the PID of the newly spawned bar process in a file, lets call it pidfile . This can be a newline delimited list of PIDs as well.

When you call foo stop use pkill -F pidfile to kill all running processes with PIDs matching those in pidfile

Alternatively you could use pkill to dicover the PIDs of all processes matching certain criteria when you called foo stop . This might be easier, but may also be more fragile.

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