Killing a process gently

We have discussed kill before.

Start an application you don’t care about, say an instance of a text editor like gedit. Open a terminal and run top with the -b (for batch) option, and pipe it through grep with a phrase that should isolate the process (like “gedit”). Like this:

greg~$ top -b | grep "gedit"
7360 greg 20 0 32724 18m 10m S 0 0.6 0:00.64 gedit

That line starting with 7360 will keep printing out until you hit Ctrl-C or some other brutish command to stop the top process. But now you know that the process number is 7360 (or whatever it is on your machine, most assuredly different). So you can kill it using the kill command. The whole thing looks like this:

greg~$ top -b | grep "gedit"
7360 greg 20 0 32724 18m 10m S 0 0.6 0:00.64 gedit
7360 greg 20 0 32724 18m 10m S 0 0.6 0:00.64 gedit

greg~$ kill 7360
greg~$ top -b | grep "gedit"


Notice that the second time around, there was no output, because the process was dead.

Fine. But what if you are not sure if you want to kill the process, but you do want to know that it is there, in your sights, in case you want to do it it? In other words, you have a process ID but are not sure what the status of the process is.

Kill with the -0 flag will return a 0 for a process that is running (zero is the normal returned value for normal or successful things). But it won’t kill the process. Think of -0 (and that is a zero) as the “don’t really kill it” flag.

This may seem a bit esoteric, but when you need to know how to do it, you will appreciate the tip. Just come to this blog and search for the string “kill the process gently” and you’ll be good to go.

I totally stole this from here.


  1. #1 charfles
    September 25, 2008

    Instead of using top’s batch mode it might be easier to use “ps”. You won’t have to kill it and it can give the command line arguments the process was executed with:

    $ sleep 60
    $ sleep 65
    $ ps ax | grep sleep
     2183 pts/0    S      0:00 sleep 60
     2184 pts/0    S      0:00 sleep 65
  2. #2 charfles
    September 25, 2008

    ps. put sleep in the background to actually test my above example:

    $ sleep 60 &
    $ sleep 65 &
  3. #3 AnonymousCoward
    September 25, 2008

    One trick I like is to use single character bracket expressions to prevent self referential matches.

    $ ps -eaf |grep konsole
    deepak 25983 23839 0 22:02 pts/2 00:00:00 grep –colour=auto konsole
    deepak 32046 6385 0 Sep21 ? 00:00:18 konsole [kdeinit]


    $ ps -eaf |grep konsol[e]
    deepak 32046 6385 0 Sep21 ? 00:00:18 konsole [kdeinit]

  4. #4 Dave S
    September 26, 2008

    Using ps or top before hand to get the process number is really only necessary if you have multiple processes with the same name and only want to kill one.

    Otherwise simply us “killall” instead, e.g. killall -9 gedit