java 正在验证应用程序,使用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.

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.

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.

Thank you very much.

解决方案

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值