Linux: Kill process based on arguments

How can I kill a process based on its command line arguments?
killall, pgrep, and pkill seem to only work based on the process name.

I need this to be able to differentiate between a number of applications running inside Java virtual machines, where java is the process name for all of them and the actual application name can be found by looking at the command line arguments.

This can be done manually with ps aux | grep myapp.jar and then manually killing the pid from the output, but I’d like a command to do something equivalent automatically.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

pgrep/pkill take a -f flag. From the man page:

-f    The pattern is normally only matched against the process name.
      When -f is set, the full command line is used.

For example:

$ sleep 30& sleep 60&
[1] 8007
[2] 8008

$ pkill -f 'sleep 30'
[1]  - terminated  sleep 30

$ pgrep sleep
8008

Method 2

Replace argument below with a regular expression that must much the full command line of a process:

kill `ps -eo pid,args --cols=10000 | awk '/argument/ && $1 != PROCINFO["pid"] { print $1 }'`

Method 3

You can use htop to view all currently running processes with their command line arguments and to kill a selected process.

Method 4

If you don’t have pkill or whatever, just use proc/[1-9]*/cmdline

grep -a myapp.jar /proc/[1-9]*/cmdline|tr '' ' '|grep -v grep|awk -F/ '{print $3}'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x