The easiest way: use pkill
to kill a running process by name.
Let’s say you have a background task running:
Those sleep
commands will run for 60 seconds and 600 seconds, respectively.
Kill a process by name
If we want to kill them sooner, we can just pkill
them by name:
pkill
works similar to killall
—both commands will kill all matching processes. What if we only want to kill one?
Kill a process by ID
Maybe you have multiple processes running with similar names, and you only want to kill one of them. In that case, you can run kill {pid}
.
In the example above, pgrep
returned the process IDs for both sleep
commands:
To stop just one of them I could have run kill 26912
, and left the other one untouched. But which PID is which? They’re going to run for different amounts of time, and I want to make sure I kill the right one.
How to find process IDs
In the screenshot above, pgrep
didn’t differentiate between the two sleep
commands; it just gave us the PIDs. The traditional way to find PIDs is via ps aux
; specifically: ps aux | grep {name_to_look_for}
.
However, I find pgrep -lf
to be a nicer option1:
Now we see the processes with their details, and can decide what to do from here.
What if pkill and kill don’t work?
By default, pkill
and kill
send processes a SIGTERM, which is the signal to terminate gracefully. Sometimes though, that doesn’t work. When it doesn’t, you may need to send a SIGKILL via kill -9 {PID}
or pkill -9 {name}
.
Sending SIGKILL does carry some risks, so you shouldn’t do it unless you know it’s ok. For more details, see this helpful article.
Helpful Links
- The differences between pkill and killall – Stack Exchange
- SIGTERM vs SIGKILL
Notes
-l
is “long output”, which gives the process name in addition to its PID e.g.48289 sleep
. When combining-l
and-f
we get the process’s full command e.g.48289 sleep 100
↩︎