How to Stop a Background Process When the Foreground Process Finished Completing the Task

Need to stop b.sh when a.sh is finished. Both scripts must run in parallel one must not wait for the other. b.sh contains the profiling of the process a.sh. When I run the script while loop does not stop. I couldn't use $! to kill the background process because other processes are running in the background created from a.sh script file.

Contents of a.sh:

#!/bin/bash 
pid=$$
export pid
./b.sh &
b_id=$!
#load time
docker load<ubuntu.tar
id=$(docker images -a | awk '{print $3}' | awk 'NR==2')
docker run -t --rm $id
echo "Container started"
pkill -P $b_id

Contents of b.sh:

#!/bin/bash
while true; do
some profiling code
done
2

1 Answer

There's no need to use pkill, which is normally used to find a PID from a pattern such as the process name, as you already have the PID of the b.sh script. Just using plain old kill will do, replace:

pkill -P $b_id

with:

kill $b_id

I'm guessing that you used pkill -P $Pb_id as you want to kill all child processes of b.sh, this command kills all of the child processes, but not the process itself. There's no problem in using them both, so pkill all of the child processes first, then kill the parent process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest