how to kill a process in java after completion of a job in java
I have a code similar to:
URL url = Activator.getDefault().getBundle().getEntry("/resources/server.bat");
String fileURL = FileLocator.toFileURL(url).toString();
String commandLine = "cmd.exe /c start " +fileURL;
Process process= Runtime.getRuntime().exec(commandLine);
How can I kill the pro开发者_开发知识库cess as soon as the work is done in java
process.destroy()
But it won't have control over the process started from server.bat
those are separately started
Runtime.exec creates a Process which actually is a sub-shell on the target machine. This particular sub-shell could be killed or terminated using process.destroy(); method. But the particular subprocess may have spawned many other subprocesses for other external commands in the batch or shell script. If we kill the parent process, the child processes may not be killed and that may worsen the situation.
First of all, you must already know that, when you execute a Java program it runs on a JVM (Java Virtual Machine). Thus when you execute the “tasklist” command you’ll not be able to see your Java process name.
Fortunately when you have the JDK installed you can see all the java processes which are running on your machine by using the Java Virtual Machine Process Status Tool. To use it just type the “jps” command:
As you can see the “jps” command gives you all the needed information like the PID and the java process name. So by using the java process name you are now able to kill the desired process.
Here you can find the magic command line:
for /f "tokens=1" %i in ('jps -m ^| find "JAVA_PROCESS_NAME"') do ( taskkill /F /PID %i )
This command will execute the “jps -m” command and get the PID of the java processes which contain the given “JAVA_PROCESS_NAME” and execute a “taskkill /F /PID” over. N.B.1: replace the “JAVA_PROCESS_NAME” by your own process name. N.B.2: For the bat files put a double % (%%i) instead of one.
For example, to kill the Eclipse program type this command:
C:\Users\YannickL>for /f "tokens=1" %i in ('jps -m ^| find "Eclipse"') do ( taskkil l /F /PID %i ) C:\Users\YannickL>(taskkill /F /PID 5076 ) SUCCESS: The process with PID 5076 has been terminated.
精彩评论