Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a java process in windows programmatically

I have many executable jar files which I am running in a windows server. Sometime, I need to redeploy some of the applications. For that, I need to first stop the existing process and then start the new process. In linux environment I am using pkill to kill the process based on the jar file name. But in windows, all the java processes will be named as "java.exe" only. I need to write a batch file to do this start and stop operations. How can I kill the jar file based on the name.

Assume that my jar file is named as common-api.jar. Running the command jps -ml | find "common" would give the result as

6968 common-api.jar

I can kill the process by taskkill /f /PID 6968

But How can I extract the process id from the first command and pass it to the taskkill command ?

like image 646
Yadu Krishnan Avatar asked Jan 29 '15 07:01

Yadu Krishnan


People also ask

How do you kill a java process in Windows?

If you want to kill all java.exe processes : taskkill /F /IM java.exe /T .

How do I find and kill a java process in Windows?

start "MyProgramName" java java-program.. Here start command will open a new window and run the java program with window's title set to MyProgramName. Your Java program will be killed only.

How do you kill a java process gracefully?

Graceful-kill-java allows you to gracefully kill java processes, which 'taskkill pid' and 'wmic ... call terminate' cannot do. TL;DR Use the command graceful-kill-java. bat [command line partial text] to kill all java processes whose command line contains the partial text.


2 Answers

for /f "delims= " %%a in ('jps -ml ^| find /i "common"') do set PID=%%a
taskkill /f /PID %PID%

or from command prompt:

for /f "delims= " %a in ('jps -ml ^| find /i "common"') do set PID=%a
like image 107
npocmaka Avatar answered Oct 11 '22 12:10

npocmaka


In vbscript we can do something like that just give a try with it :

Option Explicit
Call KillProcessbyName("common-api.jar")
'**********************************************************************************************
Sub KillProcessbyName(FileName)
    On Error Resume Next
    Dim WshShell,strComputer,objWMIService,colProcesses,objProcess
    Set WshShell = CreateObject("Wscript.Shell")
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
    For Each objProcess in colProcesses
        If InStr(objProcess.CommandLine,FileName) > 0 Then
            If Err <> 0 Then
                MsgBox Err.Description,VbCritical,Err.Description
            Else
                objProcess.Terminate(0) 
            End if
        End If
    Next
End Sub
'**********************************************************************************************
like image 32
Hackoo Avatar answered Oct 11 '22 13:10

Hackoo