BashItOut

Killing processes in Linux

A quick way to find a running process that you know the name of is to use ps:

ps aux | grep processname

or to filter out the grep process:

ps aux | grep -v grep | grep -i processname

Then to kill it you could use kill and the PID (Process ID) reported by ps:

sudo kill -9 1337

That does works, but it’s cumbersome to type, especially if you’re killing things often, so let’s look at a better way…

Introducing pgrep and pkill

For demonstration purposes, let’s setup a python SimpleHTTPServer and detach it from the command line:

nohup python -m SimpleHTTPServer &

We can now see the PID ps as before:

ps aux | grep -i http

But we can also use pgrep

$ pgrep -fl Simple
1337 python -m SimpleHTTPServer

Here the -f option allows pgrep to search the process name and it’s arguments, and the -l option lists the process name in it stdout instead of just the PID by default.


Now that we know that pgrep has found our process, we can use pkill to terminate it:

pkill -f Simple

And we can check it’s died using pgrep again:

pgrep -fl Simple

If you’ve got a stubborn process, you can also send an optional signal to pkill, just as you can with kill, just make sure it’s the first argument:

pkill -9 -f Simple

So to recap, find your process by name with pgrep (optional) and terminate it by name with pkill:

$ pgrep -fl Simple
1337 python -m SimpleHTTPServer
$ pkill -9 -f Simple
[1]+  Killed    nohup python -m SimpleHTTPServer
$ 

Tags: Linux

blog comments powered by Disqus

About

@MTerzza Twitter Icon

+MikeTerzza Google Plus Icon

Atom | RSS RSS Icon

Recent Posts:

Monitoring the progress of dd

RTL SDR Frequency Drift Offset

Random Seriousness with Python and Password Generation

Random Fun and the Busy Linux Geek

Ampersands & on the command line