Search code examples
bashchild-processspawnspawning

Bash: spawn child processes that quit when parent script quits


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.


Solution

  • 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.