Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/
like image 279
sid_com Avatar asked Oct 16 '25 04:10

sid_com


2 Answers

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 ;)

like image 145
Marcus Borkenhagen Avatar answered Oct 18 '25 17:10

Marcus Borkenhagen


The $_ variable is the PID of your last background job. Use it to kill your process. To catch errors/signals use trap (man bash has an example).

like image 44
n. 1.8e9-where's-my-share m. Avatar answered Oct 18 '25 18:10

n. 1.8e9-where's-my-share m.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!