前言
在不同系統(tǒng)的操作下互捌,該如何關(guān)閉進(jìn)程呢?
下面就讓我們一起來看看吧!
window系統(tǒng)下:
package com.silin;
import java.io.IOException;
import java.lang.management.ManagementFactory;
public class Test06 {
public static void main(String[] args){
//獲取系統(tǒng)類型
String os = System.getProperty("os.name");
//判斷是系統(tǒng)類型
if(os.toLowerCase().startsWith("win")){
System.out.println(os);
//window系統(tǒng)
String killCmd = "taskkill /f /im LogViewPro.exe";
String killCmd1 = "taskkill /f /im wps.exe";
Process p;
try {
p = Runtime.getRuntime().exec(killCmd);
p = Runtime.getRuntime().exec(killCmd1);
int runnngStatus = p.waitFor();
System.out.println("已殺" + runnngStatus);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
linux系統(tǒng)下:
package com.silin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CloseLinuxProcess {
public static void main(String[] args) {
String PID = getPID("java -jar test.jar");
closeLinuxProcess(PID);
}
/**
* 獲取Linux進(jìn)程的PID
* @param command
* @return
*/
public static String getPID(String command){
BufferedReader reader =null;
try{
//顯示所有進(jìn)程
Process process = Runtime.getRuntime().exec("ps -ef");
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = reader.readLine())!=null){
if(line.contains(command)){
System.out.println("相關(guān)信息 -----> "+command);
String[] strs = line.split("\\s+");
return strs[1];
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* 關(guān)閉Linux進(jìn)程
* @param Pid 進(jìn)程的PID
*/
public static void closeLinuxProcess(String Pid){
Process process = null;
BufferedReader reader =null;
try{
//殺掉進(jìn)程
process = Runtime.getRuntime().exec("kill -9 "+Pid);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = reader.readLine())!=null){
System.out.println("kill PID return info -----> "+line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(process!=null){
process.destroy();
}
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
}
}
}
}
}
代碼是直接調(diào)用終端,對終端進(jìn)行操作。因window與linux看看進(jìn)程的方式不同蒲稳。