Search code examples
shellprocessbusybox

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.


Solution

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