Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a background process created in a script

Tags:

bash

shell

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?

like image 258
Nan Hua Avatar asked Dec 18 '22 18:12

Nan Hua


2 Answers

(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

like image 148
Michael Ballent Avatar answered Jan 18 '23 20:01

Michael Ballent


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)
like image 43
Facundo Victor Avatar answered Jan 18 '23 21:01

Facundo Victor