Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

killing the background process in a shell script

I have a script that starts background processes.

#!/bin/sh

./process1.sh &
./process2.sh &

I need to kill these processes using a separate script. Here is what I did:

#!/bin/sh
# the kill.sh

pid=$(ps | grep './process1.sh' |grep -v grep| awk '{print $1}')
kill -9 $pid

Question time:

  1. When the kill.sh is called processes are stoped. But I get the message

    "sh: you need to specify whom to kill". Why is that?

  2. After I kill the process using the described script, it doesn't stop immediately.For a while I see the output on the screen as if the process is still running. Why?

  3. What could be an alternative solution to kill the processes?

Worth to mention that I am working with busybox do I have limited choice of utilities.

like image 870
sol_oi Avatar asked Oct 10 '12 08:10

sol_oi


1 Answers

You could store the process ids in a temporary file like this:

#!/bin/sh

./process1.sh &
echo $! > /tmp/process1.pid
./process2.sh &
echo $! > /tmp/process2.pid

and then delete it with your script. $! returns the PID of the process last executed.

kill -9 `cat /tmp/process*.pid`
rm /tmp/process*.pid

Make sure the process*.pid files get deleted after the corresponding script is finished.

like image 127
mana Avatar answered Nov 02 '22 09:11

mana