1

I'm writing a script to stop an application. Sometimes the application doesn't want to stop. So after a several minute pause, if the application is still running I want to kill it. After a number of failures of the kill command, I tried adding the -9 to force stop it. This doesn't seem to work. Does anyone know how I can get this to function, even if I need to use a different command, I'm open to new things. :-)

Following is my command line:

ps -ef|grep -v grep|grep <process_name>|awk -F' ' '{print $2}' |xargs kill -9

Thanks in advance.

  • 6
    Seems to me this entire pipeline can be reduced to: pkill -9 <process_name> – muru Jun 1 '17 at 19:00
  • grep -v grep | grep «process_name» could be done better as grep «[p]rocess_name». (and if you did have to do it the first way then swapping the order would be more efficient.) – ctrl-alt-delor Jun 1 '17 at 20:39
  • what does ps -ef | grep -v grep | grep «process_name» | awk -F' ' '{print $2}' return? What about ps -ef | grep -v grep | grep «process_name» ? – ctrl-alt-delor Jun 1 '17 at 20:42
  • @richard and it will still be as useless as cat /path/file | grep xpto. pkill -9 <procname> should be enough... – user34720 Jun 1 '17 at 20:43
  • @nwildner I understand all of the words (except xpto), but I have no idea what you are saying. Something will still be as useless as something, but what I do not know. Please help, by re-writing comment. – ctrl-alt-delor Jun 1 '17 at 20:48
6

@muru was correct, but lately I've found that using the '-f' option to pkill is preferred. Matches against the entire process and argument list. Here we have a few servers running Tomcat processes and Logstash (sending data to Elastic). So 'kill -9 java' to stop the Tomcat process also kills the Logstash process.

pkill -9 -f 'pattern to match'

Example:

pkill -9 -f '/opt/tomcat/'
2

Example how to close php processes in batch. php you can replace using whatever your process has name:

ps -aux | grep php | awk '{print $2}' | xargs kill -9
  • The point made in a number of the comments and summarised nicely by the accepted answer is that such a pipeline is totally unnecessary. Even without pkill one can do ps -aux | awk '$11 ~ /[p]hp/ {print $2}' | xargs kill – roaima Apr 22 '20 at 17:16
  • Bear in mind that the only signal that every process is forced to obey is the KILL signal. The result of rest of the signals it depends on how such a program was coded. – sebelk Apr 22 '20 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.