3

I'd like to spawn several child processes in Bash, but I'd like the parent script to remain running, such that signals send to the parent script also affect the spawned children processes.

This doesn't do that:

parent.bash:

#!/usr/bin/bash

spawnedChildProcess1 &
spawnedChildProcess2 &
spawnedChildProcess3 &

parent.bash ends immediately, and the spawned processes continue running independently of it.

Geremia
  • 4,745
  • 37
  • 43

2 Answers2

7

If you want your parent to not exit immediately after spawning its children, then as Barmar told you, use wait.

Now, if you want your child processes to die when the parent exits, then send them a SIGTERM (or any other) signal just before exiting:

kill 0

(0 is a special PID that means "every process in the parent's process group")

If the parent may exit unexpectedly (e.g. upon receiving a signal, because of a set -u or set -e, etc.) then you can use trap to send the TERM signal to the child just before exiting:

trap 'kill 0' EXIT

[edit] In conclusion, this is how you should write your parent process:

#!/usr/bin/bash
trap 'kill 0' EXIT
...
spawnedChildProcess1 &
spawnedChildProcess2 &
spawnedChildProcess3 &
...
wait

That way no need to send your signal to a negative process ID since this won't cover all the cases when your parent process may die.

xhienne
  • 5,738
  • 1
  • 15
  • 34
3

Use wait to have the parent process wait for all the children to exit.

#!/usr/bin/bash

spawnedChildProcess1 &
spawnedChildProcess2 &
spawnedChildProcess3 &

wait

Keyboard signals are sent to the entire process group, so typing Ctl-c will kill the children and the parent.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • However, `kill -s 19 \`pgrep -f "parent.bash"\`` doesn't send that signal to the children processes. (Maybe this is a separate question.) – Geremia Mar 08 '21 at 23:32
  • 2
    That only kills the parent process, not the whole process group. `kill -INT -$(pgrep -f "parent.bash")` A negative process ID means to kill the process group. – Barmar Mar 08 '21 at 23:34
  • Found answer: "[What's the best way to send a signal to all members of a process group?](https://stackoverflow.com/a/15139734/1429450)." – Geremia Mar 08 '21 at 23:45
  • Your command returns an error that the negative number doesn't correspond to a process. – Geremia Mar 11 '21 at 20:17
  • It should work if the process group hasn't finished. – Barmar Mar 11 '21 at 20:20
  • It's the same as the answers in the question you linked to. – Barmar Mar 11 '21 at 20:20