views:

360

answers:

7

How do I kill the last spawned background task in linux?

Example:

doSomething
doAnotherThing
doB &
doC
doD
#kill doB
????
A: 

You need its pid... use "ps -A" to find it.

jldupont
A: 

Just use the killall command:

killall taskname

for more info and more advanced options, type "man killall".

zakk
I think killall is a bit aggressive when you actually have easy access to the PID. And dangerous, too, especially if you're root
Dave Vogt
+10  A: 

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

roe
A: 

skill doB

"skill" is a version of the kill command that lets you select one or multiple processes based on a given criteria.

gte525u
A: 

Dont take my answer to harsh but... is there a reason for that Background process. The famous kill command can achieve what you want... but just "killing" the process seems to me like a quick solution, instead of so called "clean" solution.

Just my 2 cents

bastianneu
+3  A: 

You can kill by job number. When you put a task in the background you'll see something like:

$ ./script &
[1] 35341

That [1] is the job number and can be referenced like:

$ kill %1
$ kill %%  # Most recent background job

To see a list of job numbers use the jobs command. More from man bash:

There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job.

John Kugelman
+1  A: 

The following command gives you a list of all background processes in your session, along with the pid. You can then use it to kill the process.

jobs -l

Example usage:

$ sleep 300 &
$ jobs -l
[1]+ 31139 Running                 sleep 300 &
$ kill 31139
Dave Vogt