开发者

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

开发者 https://www.devze.com 2023-03-21 20:45 出处:网络
How could I manage, that the morbo-server called here as a ba开发者_Go百科ckground-process will be shutdown/killed automatically if I close the Firefox-window or if I stop this script in some way?

How could I manage, that the morbo-server called here as a ba开发者_Go百科ckground-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/


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


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


In bash $_ is the last argument to the previous command. To kill a background job you'll have to use job numbers (or PID). An example of using job number:

[15:29:29 ~]$ gvim &
[2] 28509
[15:29:31 ~]$ kill %2
[15:29:39 ~]$
[2]+  Terminated              gvim
[15:29:42 ~]$

[2] is the job number and is shown when you launch the background process.

0

精彩评论

暂无评论...
验证码 换一张
取 消