Improve post by making commands more robust
This commit is contained in:
parent
e4e4322aa5
commit
676a91f23d
@ -142,7 +142,7 @@ Finally, create the main script which will start child scripts and restart them
|
|||||||
```bash
|
```bash
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
echo "My pid is $$. You know what to do ( ͡° ͜ʖ ͡°)"
|
echo "My pid is $$. You know what to do ( ͡° ͜ʖ ͡°)"
|
||||||
echo "You can also send me signal with 'killall `basename $0` ...'"
|
echo "You can also kill me with 'kill -s INT -\`pgrep -f `basename $0`\`'"
|
||||||
|
|
||||||
pids=() # we will store the pid's of child scripts here
|
pids=() # we will store the pid's of child scripts here
|
||||||
scripts_to_be_executed=("./script1" "./script2")
|
scripts_to_be_executed=("./script1" "./script2")
|
||||||
@ -151,7 +151,9 @@ kill_childs(){ # wow, this sounded wild
|
|||||||
for pid in "${pids[@]}"
|
for pid in "${pids[@]}"
|
||||||
do
|
do
|
||||||
echo killing "$pid"
|
echo killing "$pid"
|
||||||
kill "$pid"
|
# -P: kill all the processes whose parent process is 'pid'
|
||||||
|
# see how we are creating processes below
|
||||||
|
pkill -P "$pid"
|
||||||
done
|
done
|
||||||
pids=()
|
pids=()
|
||||||
}
|
}
|
||||||
@ -162,12 +164,14 @@ restart_scripts(){
|
|||||||
# for each script in the list
|
# for each script in the list
|
||||||
for script in "${scripts_to_be_executed[@]}"
|
for script in "${scripts_to_be_executed[@]}"
|
||||||
do
|
do
|
||||||
# run the script and store its pid.
|
# Run the script and store its pid.
|
||||||
# '&' at the end of command is important otherwise
|
# note the '&' at the end of command. Without it the script will
|
||||||
# the script will block until its execution is finished.
|
# block until its execution is finished. Also we are putting it
|
||||||
$script &
|
# into braces because we want to create a "process group" so that
|
||||||
pid=$!
|
# we can kill all its children later by specifying parent pid
|
||||||
pids+=("$pid")
|
# (useful if you have pipes (|) or other &'s in your script!)
|
||||||
|
($script) &
|
||||||
|
pids+=("$!")
|
||||||
done
|
done
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -194,7 +198,7 @@ Here is an example run:
|
|||||||
```
|
```
|
||||||
❯ ./trap_multiple
|
❯ ./trap_multiple
|
||||||
My pid is 3124123. You know what to do ( ͡° ͜ʖ ͡°)
|
My pid is 3124123. You know what to do ( ͡° ͜ʖ ͡°)
|
||||||
You can also send me signal with 'killall trap_multiple ...'
|
You can also kill me with 'kill -s INT -`pgrep -f trap_multiple`'
|
||||||
Hello from ./script1. i is 1
|
Hello from ./script1. i is 1
|
||||||
Hello from ./script2. i is 1
|
Hello from ./script2. i is 1
|
||||||
Hello from ./script2. i is 2
|
Hello from ./script2. i is 2
|
||||||
|
Loading…
Reference in New Issue
Block a user