问题描述
我目前正在JAVA中构建一个只能执行一次的应用程序。所以我目前正在使用一个锁定文件,在其中我编写当前执行的PID。
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.
因此,每当此应用程序启动时,它将打开文件(如果存在)并尝试检测文件中写入的PID是否实际正在运行。
So whenever this application will start, it will open the file (if it exists) and try to detect if the PID written in the file is actually running.
这可以防止在解锁文件之前我的应用程序崩溃的问题。
This prevent the problem where my app crash before unlocking the file.
我需要这个才能同时工作windows(XP,7或8)和linux(所有用户都使用基于debian的发行版)。
I need this to work both on windows (XP,7 or 8) and linux (all the users are on debian based distros).
这里有一些代码可以让你更好地了解我想要的内容执行:
Here's some code to give you a better picture of what I want to do :
//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
*/
}
我试图找到有关此主题的文档,但我没找到任何有用的东西。
I have tried to find documentation on the subject, but I didn't manage to find anything useful yet.
非常感谢。
推荐答案
在posix系统上,查询pid是否正在运行的典型方法是向其发送空信号,例如 kill(pid,0)
。如果呼叫成功,则该过程存在;如果它返回 ESRCH
则不会。这自然受到不可避免的竞争条件的影响,实际情况比实际情况要少得多。不太统一的方法是读取/ proc文件系统(如果操作系统有一个),这是更多的工作,相同的事情,并仍然受到相同的竞争条件。
On posix systems the typical way to query if a pid is running is to send it a null signal e.g. kill(pid, 0)
. If the call succeeds the process exists; if it returns ESRCH
it does not. This is naturally subject to unavoidable race conditions which amount to much less in reality than they do in theory. Less uniform ways are to read the /proc file system (if the OS has one) which is more work, amounts to the same thing, and is still subject to the same race conditions.
请注意,pid lockfile技术可以是双层的。也就是说,正在运行的进程会创建文件,锁定它并写入其pid。它在运行期间保持锁定,因此这几乎消除了上述查询进程是否正在运行的需要,因为如果进程崩溃,文件锁定将自动释放,即使该文件仍然存在。逻辑是这样的:
Note that pid lockfile technique can be two-tiered. That is, the running process creates the file, locks it, and writes its pid. It holds the lock for the duration of its run and thus this pretty much does away with the above need to query whether the process is running because if the process crashes the file lock will be automatically released even though the file still exists. The logic goes like this:
if file exists
if can get lock
prev instance died unnaturally
continue with this new process
else
instance already running
else
good to go, continue with new process
这种技术也有竞争条件。
This technique also has race conditions.
我不记得足够的Java说它是否有 kill
的包装器或文件锁定系统调用,如 flock
, lockf
实现此方案需要 fcntl
。
I don't remember enough Java to say whether it has wrappers for kill
or file locking syscalls like flock
, lockf
and fcntl
required to implement this scheme.
这篇关于使用JAVA中的PID验证进程是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!