Linux

How to Kill All Background Processes in One Command on Linux

For executing batch jobs invisibly, system administrators usually schedule jobs in crontab or execute them in the background. Of course you can use fg to flip the jobs from the background to foreground and cancel it for every process, but what about hundreds of job in the background? There’s a smart way to do it in one command. For example:
[root@test ~]# sleep 60 & sleep 60 & sleep 60 & sleep 60 &
[1] 25570
[2] 25571
[3] 25572
[4] 25573
[root@test ~]# jobs
[1]   Running                 sleep 60 &
[2]   Running                 sleep 60 &
[3]-  Running                 sleep 60 &
[4]+  Running                 sleep 60 &

Now we have 4 jobs, and their process ID are as:
[root@test ~]# jobs -p
25570
25571
25572
25573

You can use a pair of back quotes like the following to identify target ID to kill:
[root@test ~]# kill -9 `jobs -p`
or
[root@test ~]# kill -9 $(jobs -p)
[1]   Killed                  sleep 60
[3]-  Killed                  sleep 60
[root@test ~]#
[2]-  Killed                  sleep 60
[4]+  Killed                  sleep 60
[root@test ~]# jobs

No more jobs.

Leave a Reply

Your email address will not be published. Required fields are marked *