java中判断该进程是否已经启动

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bitwei83/article/details/84354636
思路从http://blog.csdn.net/genww/article/details/6119731所得,稍作修改。

要求做一个Java控制台程序,并要求程序不能同时重复运行。此功能可以通过调用jps命令实现。
方法:

public class Test {

public static void main(String[] args)
{
try {
boolean run = checkPidInProcess(Test.class.getSimpleName());
if (!run) {
System.out.println("Only one.");
} else {
System.out.println("More than one.");
System.exit(0);
}
Thread.sleep(10 * 60 * 1000);
}
catch (Exception e) {
e.printStackTrace();
}

}

private static boolean checkProcessInProcess(String className)
throws Exception
{
InputStream in = null;
String line = null;

try {
in = Runtime.getRuntime().exec("jps").getInputStream();
BufferedReader b = new BufferedReader(new InputStreamReader(in));

int count = 0;
while ((line = b.readLine()) != null) {
if (line.contains(className)) {
count++;
if (count > 1) {
return true;
}
}
}
return false;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
if (in != null) {
in.close();
}
}
}
}


=====================================================
以下为修改:
上面的放在在eclipse里面执行的时候是成功的,但是如果要将程序打包成jar,并通过控制台或者批处理的方式执行时,就会发生问题。因为当导出jar包时,jps命令只会给出形如"1234 jar"这样的文字,没有类名。这时的处理方式:
1. 将jar包名命名成和类一样的名字。
2. 将上面代码中的一段改成
in = Runtime.getRuntime().exec("jps -mlvV").getInputStream();
带了参数的jps命令可以写出jar包名,这样就可以实现功能了。

注:注意jar包名的大小写。
展开阅读全文

WinCE怎么判断进程是否已经存在???

12-08

在网上找到这端代码rn[code=C#]rnusing System;rnusing System.Collections.Generic;rnusing System.Text;rnusing System.Runtime.InteropServices;rnrnnamespace WindowsApplication1rnrn /// rn /// MobileUtilsrn /// rn public class MobileUtilsrn rnrn /// rn /// 判断某个进程是否已经存在rn /// rn /// rn /// rn public static bool IsProcessRunning(string processName)rn rn int hMutex;rn hMutex = CreateMutex(null, false, processName);rnrn if (GetLastError() == ERROR_ALREADY_EXISTS)rn rn ReleaseMutex(hMutex);rn return true;rn rn return false;rn rnrn /// rn /// GetLastErrorrn /// rn /// rn [DllImport("coredll.Dll")]rn private static extern int GetLastError();rnrn /// rn /// ReleaseMutexrn /// rn /// rn /// rn [DllImport("coredll.Dll")]rn private static extern int ReleaseMutex(int hMutex);rnrn /// rn /// CreateMutexrn /// rn /// rn /// rn /// rn /// rn [DllImport("coredll.Dll")]rn private static extern int CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);rnrn /// rn /// rn /// rn private const int ERROR_ALREADY_EXISTS = 0183;rnrn /// rn /// SECURITY_ATTRIBUTESrn /// rn [StructLayout(LayoutKind.Sequential)]rn private class SECURITY_ATTRIBUTESrn rnrn /// rn /// rn /// rn public int nLength;rnrn /// rn /// rn /// rn public int lpSecurityDescriptor;rnrn /// rn /// rn /// rn public int bInheritHandle;rnrn rn rnrn[/code]rnrn我按照这个做的,我的工程名字是AProject,可是检测时候时候即使我已经开启了这个软件,再次开启时还是检测不到开启,请问CreateMutex(null, false, processName);中得软件名字该写什么呢? 论坛

没有更多推荐了,返回首页