tags:

views:

512

answers:

5

Is there a way to stop a java program running using a shell script by knowing the name alone.I am using ksh shell

A: 

You can use pkill:

pkill your_java_program_name

This would work if you run only one instance of the your program is running.

Adam Matan
+1  A: 

You can use jps identifying the process-id associated with the name of the started java-program (jps is a process-manager for java-programs). With this id you can kill the process normally.

Mnementh
assuming my java file name is test.java and is running how to find it?
Harish
+1 for introducing me to jps :)
sfussenegger
@Harish: After compiling it and executing it will be shown as 'test'. If you package it in an executable jar (test.jar) and execute via 'java -jar test.jar' jps shows 'test.jar'.
Mnementh
+2  A: 

Add a unique property to the JVM to identify it easily, e.g. for test.class

java -Duniquename=1 test

To kill it:

ps ax | grep uniquename | grep -v grep | awk '{print $1}' | xargs kill
diciu
Its throwing error.I am using ksh shell
Harish
what error are you getting ?
Valentin Rocher
It works fine under KSH. Maybe you've made an error copying the command.
diciu
+1  A: 

following up on Mnementh' suggestion:

this should do the job

jps -l | grep org.example.MyMain | cut -d ' ' -f 1 | xargs -n1 kill
  • jps -l: list java process with "full package name for the application's main class or the full path name to the application's JAR file."

  • grep: choose the process you like

  • cut -d -' ' -f 1: split the output in columns using delimiter ' ' and print only the first one (the pid)

  • xargs -n1 kill: execute kill for each PID

note that you must run jps and xargs with the same user (or root) as you're running the process

sfussenegger
A: 

you can use -o option of ps to format your output,

ps -eo cmd,pid | awk '!/awk/&&/mycommand/{cmd="kill -9 "$2;system(cmd)}'
ghostdog74