gpt4 book ai didi

java - 在 JAVA 中使用其 PID 验证进程是否正在运行

转载 作者:IT王子 更新时间:2023-10-29 01:06:36 26 4
gpt4 key购买 nike

我目前正在用 JAVA 构建一个只能执行一次的应用程序。所以我目前正在使用一个锁定文件,我在其中写入当前执行的 PID。

因此,无论何时该应用程序启动,它都会打开文件(如果存在)并尝试检测文件中写入的 PID 是否实际运行。

这可以防止我的应用在解锁文件之前崩溃的问题。

我需要它在 Windows(XP、7 或 8)和 Linux(所有用户都在基于 debian 的发行版)上工作。

这里有一些代码可以让你更好地了解我想做什么:

//get the PID from the file
int pidValue = new FileReader(file).read();

//get the OS type
String os = System.getProperty("os.name").toLowerCase();

//Check PID depending of OS type
if( os.contains("nux") || os.contains("nix") ){
/*
* Check PID on Linux/Unix
*/
} else if ( os.contains("win") ) {
/*
* Check PID on Windows
*/
}

我试图找到关于这个主题的文档,但我还没有找到任何有用的东西。

非常感谢。

最佳答案

以下代码确定具有指定 pid 的进程是否正在运行。它在 Windows 7 和 Ubuntu 13 上进行了测试。在 Windows 上,它使用 apache commons-exec 来运行 tasklist 并根据它们的退出代码确定它们是否找到了指定的 pid。它通过管道将结果传递给 findstr 克服了 tasklist 总是返回 0 的事实。在 linux 上,它使用 ps 来做同样的事情。它还会抑制子进程的标准输出日志记录。

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't<ref>https://github.com/apache/storm/pull/296#discussion_r20535744</ref>
}
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;
}

关于java - 在 JAVA 中使用其 PID 验证进程是否正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21460775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com