smoczyna
smoczyna

Reputation: 519

How to kill all specific java processes

I have following search result coming from netstat:

netstat -nap | grep java | grep :::300*
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp6       0      0 :::30008                :::*                    LISTEN      81159/java          
tcp6       0      0 :::30010                :::*                    LISTEN      81164/java          
tcp6       0      0 :::30001                :::*                    LISTEN      81155/java          
tcp6       0      0 :::30002                :::*                    LISTEN      81162/java          
tcp6       0      0 :::30003                :::*                    LISTEN      81156/java          
tcp6       0      0 :::30004                :::*                    LISTEN      81161/java          
tcp6       0      0 :::30005                :::*                    LISTEN      81158/java          
tcp6       0      0 :::30006                :::*                    LISTEN      81157/java          
tcp6       0      0 :::30007                :::*                    LISTEN      81160/java  

now I need to iterate over that result, get the process id ad kill it. How can I do it ?

Upvotes: 0

Views: 236

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295443

It's not good code, but the following does what you asked for (newlines added for clarity, would be equally correct without them):

kill $(netstat -nap | awk '
  /java/ && /:::300[[:digit:]]{2}/ {
    gsub(/\/.*$/, "", $6);
    gsub(/[^[:digit:]], "", $6);
    print $6
  }
')

The second gsub is a safety measure, to ensure that only digits are printed; this reduces the chances of shell globbing or string splitting having unintended effects should the column ordering be off.


Consider using systemd or another process supervision framework to manage services, instead of doing this kind of thing with hand-written code.

Upvotes: 0

rkrankus
rkrankus

Reputation: 99

PIDS=( $(netstat -nap | grep java | grep :::300*| awk '{print $6}' | cut -d/ -f2 | xargs) ); for p in "${PIDS[@]}"; do kill -9 ${p}; done i think you can do like this but i think can be more easy way

Upvotes: 1

Related Questions