问题
How do I kill the last spawned background task in linux?
Example:
doSomething
doAnotherThing
doB &
doC
doD
#kill doB
????
回答1:
There's a special variable for this in bash:
kill $!
$! expands to the PID of the last process executed in the background.
回答2:
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 numbern
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 stoppedce
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 stringce
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.
回答3:
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
回答4:
This should kill all background processes:
jobs -p | xargs kill -9
回答5:
skill doB
skill
is a version of the kill command that lets you select one or multiple processes based on a given criteria.
回答6:
You need its pid... use "ps -A" to find it.
回答7:
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
回答8:
Just use the killall command:
killall taskname
for more info and more advanced options, type "man killall".
来源:https://stackoverflow.com/questions/1624691/linux-kill-background-task