1

I have this script.sh where I pass the path to the binaries, all apps run in the background:

./script.sh path/to/app_1 path/to/app_2 ... path/to/app_n

Here is the script:

#!/bin/bash

for app in "$@"
do
    $app &
done

All my apps are running as I expected. Some of them are just console applications without windows, but some apps have interface and I can close the window app.

I can get pid of the app, something like this:

pgrep "${app##*/}"

How to kill all apps by pids that I passed through script.bash as arguments? When I close one of the windows it should kill all known running apps.

2
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Apr 7 at 15:58
  • 1
    One suggestion, assuming the amount of processes being started is static, is to add every pid to an array, and possibly increment a variable that counts what length you expect that array to be. You could then run a while true infinite loop that either checks if the values are different, or if the pid array length is lower than expected (whichever works best), and when that is no longer true you send kill to every pid in the array and exit the script.
    – pzkpfw
    Apr 7 at 16:51

1 Answer 1

0

This should work.

declare -a _procid

_kill_them_all()
{
    for p in ${_procid[@]} ; do
        kill -9 $p 2>/dev/null
    done
    exit
}

trap _kill_them_all SIGCHLD

for app in "$@"
do
    $app  &
    _procid+=($!)
done

wait ${_procid[@]}

echo "doesn't get here if there were children"

The bash script keeps an array list of the child pids, and traps when any of the child processes exit, then the trap handler kills all the child processes.

3
  • Why do you use SIGKILL (-9)? Wouldn't be nice to use kill without any option (sending SIGTERM)? Also, you have a whole bunch of unquoted variables in your code.
    – Kusalananda
    Apr 8 at 9:44
  • @stevea, thanks, that's what i needed
    – a.wise
    Apr 10 at 19:54
  • It doesn't work on Mac, but works on Linux. Another solution: stackoverflow.com/a/37621260/12797579
    – a.wise
    Apr 13 at 9:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .