DEV Community

The best way to KILL (..a process on Mac or Linux)

Connor Bode on November 14, 2019

What's the best way to kill a process in Linux (or Mac)? Ok, I lied, it's actually probably not the best way. There are probably better ways to u...
Collapse
 
jmcphe profile image
James McPhee

In modern linuxes, you have access to pkill -signal <pattern>. Taking your example this would be:
pkill -9 manage.py
You have the ability to limit by user with -u username
You can kill the oldest process of pattern with -o and newest with -n.
One VERY nice option is -f to only match the full commandline. This is great for automated scripts in places where people like adding things to common names.
If you just want the list of process ids, then you have pgrep.

If you're stuck using an older shell, you may not have access to the $( ) subshell. You can be bourne compatible with backticks, but nesting becomes an issue.
Another old unix trick is xargs. Some people find this more natural. You pipe the list to xargs command so something like this:
ps aux | grep pattern | grep -v grep | awk '{ print $2 }' | xargs kill -9
The grep -v grep is another way to avoid the grep process instead of relying on shell to interpret the braces away. This has pros and cons, but you may find it useful.

Collapse
 
moopet profile image
Ben Sinclair

I use killall for that :()

Collapse
 
connorbode profile image
Connor Bode

Heh, that probably is a better option. I did mention that this probably is not the best way to do it, but it's still a nice story to tell with some grep & awk tricks.

Collapse
 
biros profile image
Boris Jamot ✊ /

Or, if you use the fish shell, just type kill and press <tab> to list and select the desired process.

Collapse
 
pavelloz profile image
Paweł Kowalski

Bunch of heartless killers, let them grow! They just want to feel warmth of the CPU and fill their void with memory leaks.