1

I want to check using a bat file if a Java program is already running. If its not running then start it using start javaw.

I have tried WMIC and I am only successful so far to get the PID.

WMIC process where "CommandLine like '%MyServer.jar%' and Name like '%javaw%'" get ProcessId

But how to write an if else condition in the bat file to start?

I tried using tasklist and find

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Programm is running

But for all the java applications myapp.exe will be java.exe.

Please help...

P.S: There are options for this to be done via the Java program itself, but my specific situation asks for a bat file solution.

SomethingDark
  • 13,229
  • 5
  • 50
  • 55
Tattu
  • 327
  • 1
  • 3
  • 15

1 Answers1

1

You can use jcmd.exe to see the main class of all the java processes running. The IF-ELSE syntax of the batch file is explained in the following thread

How to use if - else structure in a batch file?

jcmd | find /I /N "sun.tools.jconsole.JConsole"


IF "%ERRORLEVEL%" GTR "0" (
    jconsole.exe
)

IF %ERRORLEVEL% EQU 0 (
    echo Programm is running 
) 

This link would help with the IF construct - http://ss64.com/nt/if.html

Community
  • 1
  • 1
Akshay Gehi
  • 362
  • 1
  • 12
  • Thanks. But what do I do after that. How do I check it in IF. I already get the name using jps -m | find. jps -m | find /i "MYAPP" 6356 MYAPP localhost 1899 C:\TRAMM4.0\TRAMM\ true Now how do I write the IF else? How can I use a variable? What condition do I check? I am sorry, but I am not that familiar with CMD commands/ scripts of this scale. – Tattu Dec 18 '15 at 05:18
  • See if the example added above helps. The above program is checking if JConsole is running (main class: sun.tools.jconsole.JConsole) - if its not running it launches it. More information can be found here http://ss64.com/nt/if.html – Akshay Gehi Dec 18 '15 at 05:22
  • I feel that jcmd will be easier than jps. The output looks like : ` $ jcmd 33004 sun.tools.jcmd.JCmd` – Akshay Gehi Dec 18 '15 at 05:50
  • Thanks Akshay. That solved it for me. But when I use that for my application this is what happens, C:\FOLDER>TITLE My Server C:\FOLDER>jcmd | find /I /N "MyServer" C:\FOLDER>IF "1" GTR "0" ( cd bin set filename= C:FOLDER\ start javaw -classpath ../lib/*;MyServer.jar .cig.MyAPP.Myserver.MyServer localhost 1899 C:FOLDER\ true ) C:\FOLDER\bin>IF 0 EQU 0 (echo Programm is running ) Programm is running C:\FOLDER\bin>pause Press any key to continue . . . As you see the whole thing is being printed on the console. How can I avoid that and print only 'Program Is Running'? – Tattu Dec 18 '15 at 05:55
  • You need to turn echo off "@echo off" – Akshay Gehi Dec 18 '15 at 09:54