kill background process in 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 kill.sh is called, processes stop. But I get a message

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

  2. After I complete the process using the described script, it does not stop immediately. For a while, I see the output on the screen as if the process is still running. What for?

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

It is worth noting that I work with busybox, I have a limited selection of utilities.

+4
source share
2 answers

You can save process IDs in a temporary file as follows:

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

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

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

Make sure the process*.pid are deleted after completing the corresponding script.

+4
source

Since your kill command failed because pid empty.

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

This does not give you the pid you want. When you start a process in the background, it runs in a new shell and you will not see the output of process.sh in your ps.

What you can do is save the PID when starting background processes and kill them:

 ./process1.sh & pid1=$! # Save the previously started background PID ./process2.sh & pid2=$! # Save the previously started background PID echo $pid1 " " $pid2 > /tmp/killfile 

Then get the PID from this file and pass it kill .

+1
source

Source: https://habr.com/ru/post/1438844/


All Articles