11

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

4
  • 1
    Knowing what name? If you know the name of the executable (which normally is java though), killall is your friend. Commented Jan 25, 2010 at 11:28
  • @sfussenegger: Probably he doesn't want to kill all java-processes, but only one specific. Commented Jan 25, 2010 at 11:31
  • @Mnementh that's what I'd expect too, but from the given information this is the best thing I could recommend. Commented Jan 25, 2010 at 11:33
  • you might also want to look at start-stop-daemon if the process you're trying to kill is meant to run as a daemon Commented Jan 25, 2010 at 11:49

5 Answers 5

20

following up on Mnementh' suggestion:

this should do the job

jps -l | grep org.example.MyMain | cut -d ' ' -f 1 | xargs -rn1 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 -rn1 kill: execute kill for each PID (if any)

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

Sign up to request clarification or add additional context in comments.

2 Comments

This will also work for windows machines, but you're going to need to do some environment detection to figure out which kill to use.
@Odelya I've just added -r (--no-run-if-empty) to xargs to avoid this error.
6

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

2 Comments

It works fine under KSH. Maybe you've made an error copying the command.
'grep [u]niquename' is an alternative to 'grep uniquename | grep -v grep'
3

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.

2 Comments

assuming my java file name is test.java and is running how to find it?
@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'.
1

You can use pkill:

pkill your_java_program_name

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.