How to Kill Background Child Process in Bash

Tags: July 13, 2020 12:52 PM

Terminate Background Child Process in Bash

In Bash by child process that sent into background is still alive when main program is terminated. Take a look an example below.

#!/bin/bash

# Run a Python web server
python -m http.server src/ &

# Run SASS watcher and compiler...
sass --watch src/scss:src/css &

wait
When we run script above and terminate using CTRL+C Python and SASS are still running.

Solution to terminate Background Child Process in Bash

The solution to above problem is using shell built-in trap command.

#!/bin/bash

# Kill all child process (Python and SASS) when exit
trap "kill 0" EXIT

# Run a Python web server
python -m http.server src/ &

# Run SASS watcher and compiler...
sass --watch src/scss:src/css &

wait

Now when the script is exited all the child process even which has been sent as background process will also terminated.

References

Share on Facebook Twitter

1 comments:

Unknown said...

Gambling in Qatar - Casino & Sports Book
All the latest casino 비트 코인 토토 사이트 샤오 미 games and sports betting odds. 가상 축구 Sports betting, gambling on air jordan 18 retro varsity red online football, eSports, poker how to get jordan 18 white royal blue and more. Visit our get air jordan 18 retro varsity red website.

Post a Comment