Check if process is running on windows/linux

后端 未结 7 2169
一生所求
一生所求 2020-12-10 15:30

i have a process

Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec(filebase+port+\"/hlds.exe +ip \"+ip+\" +maxplayers \"+players+ \" -game cstrike -co         


        
7条回答
  •  孤街浪徒
    2020-12-10 15:47

    For pre Java 8 code, I'm using reflection with a fallback to catching IllegalThreadStateException. The reflection will only work on instances of ProcessImpl, but as that's what's returned by ProcessBuilder it's usually the case for me.

        public static boolean isProcessIsAlive(@Nullable Process process) {
        if (process == null) {
            return false;
        }
        // XXX replace with Process.isAlive() in Java 8
        try {
            Field field;
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            long handle = (long) field.get(process);
            field = process.getClass().getDeclaredField("STILL_ACTIVE");
            field.setAccessible(true);
            int stillActive = (int) field.get(process);
            Method method;
            method = process.getClass().getDeclaredMethod("getExitCodeProcess", long.class);
            method.setAccessible(true);
            int exitCode = (int) method.invoke(process, handle);
            return exitCode == stillActive;
        } catch (Exception e) {
            // Reflection failed, use the backup solution
        }
        try {
            process.exitValue();
            return false;
        } catch (IllegalThreadStateException e) {
            return true;
        }
    }
    

提交回复
热议问题