1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.zt.life.modules.mainPart.utils.OSUtils;
 
import com.zt.common.exception.RenException;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class ProcessUtils {
    public static long getProcessId(Process process) {
        long pid = -1;
        java.lang.reflect.Field field = null;
        try {
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                field = process.getClass().getDeclaredField("handle");
            } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
                field = process.getClass().getDeclaredField("pid");
            } else {
                throw new RenException("暂不支持该操作系统:获取进程号");
            }
            field.setAccessible(true);
            pid = Kernel32.INSTANCE.GetProcessId((Long)field.get(process));
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return pid;
    }
 
    public static void killProcess(long pid) {
        try {
            Process process = null;
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "taskkill /PID "+pid+" /T /F"});
            } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "kill -9 "+pid});
            } else {
                throw new RenException("暂不支持该操作系统:终止进程!");
            }
            int exitCode = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static boolean isProcessAlive(long pid) {
        boolean isAlive = false;
        try {
            // 根据不同的操作系统,构造不同的命令
            String os = System.getProperty("os.name").toLowerCase();
            String command;
            if (os.contains("win")) {
                // Windows 系统
                command = "tasklist /FI \"PID eq " + pid + "\"";
            } else {
                // Unix-like 系统
                command = "ps -p " + pid;
            }
 
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
 
            // 判断输出中是否包含进程信息
            while ((line = reader.readLine()) != null) {
                if (line.contains(String.valueOf(pid))) {
                    isAlive = true;
                    break;
                }
            }
 
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isAlive;
    }
 
}