How do I kill a specific process from Java code on Windows, if I have the specific PID.
            Asked
            
        
        
            Active
            
        
            Viewed 8,955 times
        
    2 Answers
20
            I don't know any other solution, apart from executing a specific Windows command like Runtime.getRuntime().exec("taskkill /F /PID 827");
        Petar Minchev
        
- 46,889
 - 11
 - 103
 - 119
 
- 
                    2add /F flag so that it kills SYSTEM processes too. – Denis Tulskiy Jan 08 '11 at 12:08
 - 
                    4As I remember, taskkill.exe is only available on Windows XP Professional and later (not in the Home Edition). You might consider shipping the code with something like pskill, just in case: http://technet.microsoft.com/en-en/sysinternals/bb896683.aspx – Jan 08 '11 at 12:26
 - 
                    @Hypnos Shipping your app with pskill is dangerous because many virus scanners detect pskill as "dangerous application" for an unknown reason. – Robert Jan 08 '11 at 13:08
 - 
                    add /T flag so that if the process is a 16 bit and launched into the ntvdm wow system, that too will be killed. Otherwise it might still run even though the launching script has been killed. – The Coordinator Mar 23 '15 at 08:40
 
2
            
            
        With Java 9, we can use ProcessHandle:
ProcessHandle.of(11395).ifPresent(ProcessHandle::destroy);
where 11395 is the pid of the process you're interested in killing.
This:
First creates an
Optional<ProcessHandle>from the givenpidAnd if this
ProcessHandleis present, kills the process usingdestroy.
No import necessary as ProcessHandle is part of java.lang.
To force-kill the process, one might prefer ProcessHandle::destroyForcibly to ProcessHandle::destroy.
        Xavier Guihot
        
- 54,987
 - 21
 - 291
 - 190