How to kill a background process created in a scri

2020-03-26 08:40发布

问题:

Suppose I input the following in a shell

(while true; do echo hahaha; sleep 1; done)&

Then I know I can kill it by

fg; CTRL-C

However, if the command above is in a script e.g. tmp.sh and I'm running that script, how to kill it?

回答1:

(while true; do echo hahaha; sleep 1; done)&
RUNNING_PID=$!
kill ${RUNNING_PID}

$! will pick up the PID of the process that is running so you can do with it as you wish



回答2:

Let's suppose that you have your bash script named tmp.sh with the next content:

#!/bin/bash
(while true; do echo hahaha; sleep 1; done)&

And you execute it! Of course, it will print hahaha to the stdout every 1 second. You can't list it with the jobs command. But... it's still a process! And it's a child in the forest of the current terminal! So:

1- Get the file name of the terminal connected to standard input:

$tty
/dev/pts/2

2- List the processes associated with the terminal (In the example we are using pts/2), and show the status with S and display in a forest format f:

$ps --tty pts/2 Sf
PID TTY      STAT   TIME COMMAND
3691 pts/2    Ss+    0:00 /bin/bash
3787 pts/2    S      0:00 /bin/bash
4879 pts/2    S      0:00  \_ sleep 1

3- Now, you can see that the example lists a sleep 1 command that is a child of the /bin/bash process with PID 3787. Now kill it!

kill -9 3787

Note: Don't kill the bash process that has the s+ statuses, is bash process that gives you the prompt! From man(ps):

s    is a session leader
+    is in the foreground process group

Recommendations:

In a case like this, you should save the PID in a file:

#!/bin/bash
(while true; do echo hahaha; sleep 1; done)&
echo $! > /path/to/my_script.pid

Then, you could just do some script to shut it down:

#!/bin/bash
kill -9 $(cat /path/to/my_script.pid)


标签: bash shell