Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux - Kill process by path

How can I kill a process by its executable's absolute file path? Hence, I want to kill all processes that were created from an executable at a given location?

ANSWER:

kill $(ps aux | grep '<absolute executable path>' | awk '{print $2}')
like image 568
goocreations Avatar asked Nov 29 '17 19:11

goocreations


2 Answers

You could use pkill(1) (or perhaps killall(1)...)

If you are coding a program you might consider using proc(5). You would then opendir(3) then loop on readdir(3) the /proc/ directory (use also stat(2) and don't forget the closedir(3)). There are pathological cases (a self-removing program).

like image 65
Basile Starynkevitch Avatar answered Sep 23 '22 14:09

Basile Starynkevitch


function killpath {
    ps aux |  awk '{print $2"\t"$11}' | grep -E '^\d+\t'"$1"'$' | awk '{print $1}' | xargs kill -SIGTERM
}

Usage:

killpath /Applications/Waterfox.app/Contents/MacOS/waterfox

What it does:

  • ps aux: List processes
  • awk '{print $2"\t"$11}': get column 2 (PID) and 11 (Executable) and separate them by a \t tab character
  • grep -E '^\d+\t'"$1"'$': Match a regex
    • ^: Beginning of line
    • \d+: one or more digits
    • \t: Tab character introduced previously
    • "$1" The input to the function, e.g. /Applications/Waterfox.app/Contents/MacOS/waterfox
    • $: End of line
  • awk '{print $1}': Get only the 1st column, the Process ID.
  • xargs: transform linebreaks to spaces

Here is how that looks on data:

# killpath /Applications/Waterfox.app/Contents/MacOS/waterfox

# ps aux
# USER           PID    %CPU %MEM  VSZ     RSS       TT  STAT STARTED   TIME     COMMAND
luckydonald      23265  04,6 10,3  9222008 1736020   ??  S    Sat10am   45:48.77 /Applications/Waterfox.app/Contents/MacOS/waterfox -foreground
luckydonald      23266  02,0 05,3  5743400  362344   ??  R    Sat10am   11:52.52 /Applications/Waterfox.app/Contents/MacOS/waterfox -foreground
luckydonald      42128  04,5 00,2  4337884   35608 s002  S+    1:17am    0:06.84 /usr/local/Cellar/docker-compose/1.23.2/libexec/bin/python3.7 /usr/local/bin/docker-compose logs -f --tail 100 r2tg

# awk '{print $2"\t"$11}'
23265   /Applications/Waterfox.app/Contents/MacOS/waterfox
23266   /Applications/Waterfox.app/Contents/MacOS/waterfox
42128   /usr/local/Cellar/docker-compose/1.23.2/libexec/bin/python3.7

# 1="/Applications/Waterfox.app/Contents/MacOS/waterfox"
# grep -E '^\d+\t'"$1"'$'
23265   /Applications/Waterfox.app/Contents/MacOS/waterfox
23266   /Applications/Waterfox.app/Contents/MacOS/waterfox

#  awk '{print $1}'
23265
23266

# xargs
23265 23266

# xargs kill -SIGTERM
kill -SIGTERM 23265 23266
like image 24
luckydonald Avatar answered Sep 22 '22 14:09

luckydonald