Verify if a process is running using its PID in JAVA

后端 未结 3 633
不思量自难忘°
不思量自难忘° 2020-12-19 13:00

I\'m currently building an application in JAVA where there can be only one execution. So I\'m currently using a lock file in which I write the PID of the current execution.

3条回答
  •  猫巷女王i
    2020-12-19 13:27

    The following code determines if a process with the specified pid is running. It was tested on Windows 7 and Ubuntu 13. On Windows it uses apache commons-exec to run tasklist and determines if they found the specified pid based on their exit code. It overcomes the fact that tasklist always returns 0 by piping the result to findstr. On linux it uses ps to do the same thing. It also suppresses stdout logging of the child process.

    public static boolean isProcessRunning(int pid, int timeout, TimeUnit timeunit) throws java.io.IOException {
        String line;
        if (OS.isFamilyWindows()) {
            //tasklist exit code is always 0. Parse output
            //findstr exit code 0 if found pid, 1 if it doesn't
            line = "cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\"";
        }
        else {
            //ps exit code 0 if process exists, 1 if it doesn't
            line = "ps -p " + pid;
                //`-p` is POSIX/BSD-compliant, `--pid` isn'thttps://github.com/apache/storm/pull/296#discussion_r20535744
        }
        CommandLine cmdLine = CommandLine.parse(line);
        DefaultExecutor executor = new DefaultExecutor();
        // disable logging of stdout/strderr
        executor.setStreamHandler(new PumpStreamHandler(null, null, null));
        // disable exception for valid exit values
        executor.setExitValues(new int[]{0, 1});
        // set timer for zombie process
        ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeunit.toMillis(timeout));
        executor.setWatchdog(timeoutWatchdog);
        int exitValue = executor.execute(cmdLine);
        // 0 is the default exit code which means the process exists
        return exitValue == 0;
    }
    

提交回复
热议问题