PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 12, 2022

[FIXED] How can I kill a process from a Java application, if I know the PID of this process? I am looking for a cross-platfrom solution

 September 12, 2022     cross-platform, java, process     No comments   

Issue

I know there are several ways to kill a process from Java, but all of these use some kind of platform-specific code that only works on Windows or Linux.

Is there a lib I can use where I can just call something like

Process.kill(pid);

Or perhaps there is a method that I can write that handles (almost) all cases of OS?

All I want to do is terminate a process, knowing it's PID already.


Solution

Since Java 9 there's ProcessHandle which allows interaction with all processes on a system (constrained by system permissions of course).

Specifically ProcessHandle.of(knownPid) will return the ProcessHandle for a given PID (technically an Optional which may be empty if no process was found) and destroy or destroyForcibly will attempt to kill the process.

I.e.

long pid = getThePidViaSomeWay();
Optional<ProcessHandle> maybePh = ProcessHandle.of(pid);
ProcessHandle ph = maybePh.orElseThrow(); // replace with  your preferred way to handle no process being found.
ph.destroy(); //or
ph.destroyForcibly(); // if you want to be more "forcible" about it


Answered By - Joachim Sauer
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing