Search code examples
bashshellshutdownbackground-process

How can I stop a background-process started from bash after the next command finished?


How could I manage, that the morbo-server called here as a background-process will be shutdown/killed automatically if I close the Firefox-window or if I stop this script in some way?

#!/bin/bash

morbo Mojolicious_Lite.pl &

firefox -new-window http://localhost:3000/

Solution

  • OK, let's solve this one.

    #!/bin/bash
    morbo Mojolicious_Lite.pl & P=$!
    trap "kill $P" INT # maybe you want EXIT here too?
    firefox -new-window http://localhost:3000/
    wait
    

    This one should work... When firefox exits the shell will wait for remaining jobs (morbo) which then can be interrupted by Ctrl-C - in which case the trap kills them.

    You can test it visually (i.e. seeing what gets executed) with

    bash -x run.sh
    

    Assuming your script is called run.sh ;)