Cork Kochi
Cork Kochi

Reputation: 1891

Terminate background job and its children on exit

The main script has a background task executing test1.sh, i am trying to stop the background task when the main task also completes

#!/bin/sh

# background process

./test1.sh &

# do while starts

x=1
while [ $x -le 30 ]
do
  echo "Welcome $x times "
  x=$(( $x + 1 ))
  sleep 1
done

exit

The ./test1.sh file contains

#!/bin/sh

while true
do
    echo "copying "
    cp logs.txt /tmp
    sleep 10
done

Or any best approach to run the background task in a separate thread of copying files and exit after the main task completes

Upvotes: 2

Views: 176

Answers (2)

Skwid
Skwid

Reputation: 29

The background process PID can be accessed by assigning it to a variable with $! and then calling it later. See below:

#!/bin/sh

# background process

./test1.sh &

# set $test1_pid to the PID of ./test1.sh & (Presumed BG [1])
test1_pid=$!

# do while starts

x=1
while [ $x -le 30 ]
do
  echo "Welcome $x times "
  x=$(( $x + 1 ))
  sleep 1
done

# Terminate BG process
kill $test1_pid

exit

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50750

Enable job control temporarily to put the background job into a separate process group, and set an EXIT trap in the main shell to broadcast a TERM signal to the background job and its children on exit.

#!/bin/sh
set -m
./test1.sh &
set +m

trap "kill -- -$!" EXIT

# rest of the program

Upvotes: 4

Related Questions