首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

跨平台获取java过程id(Process ID in Java)

2012-09-09 
跨平台获取java进程id(Process ID in Java)对于不同平台,获取java进程id有不同的方法,这个做一个总结,写一

跨平台获取java进程id(Process ID in Java)

对于不同平台,获取java进程id有不同的方法,这个做一个总结,写一个工具类。

这个工具主要进行两种尝试来获得pid:

从 java.lang.management.RuntimeMXBean获得从操作系统获得windows系统非windows系统

工具代码:

/** * Process ID in Java *  * @author lichengwu * @created 2012-1-18 *  * @version 1.0 */public final class PID {private static final Log log = LogFactory.getLog(PID.class);/** * 私有构造方法 */private PID() {super();}/** * 获得java进程id *  * @author lichengwu * @created 2012-1-18 *  * @return java进程id */public static final String getPID() {String pid = System.getProperty("pid");if (pid == null) {RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();String processName = runtimeMXBean.getName();if (processName.indexOf('@') != -1) {pid = processName.substring(0, processName.indexOf('@'));} else {pid = getPIDFromOS();}System.setProperty("pid", pid);}return pid;}/** * 从操作系统获得pid * <p> * 对于windows,请参考:http://www.scheibli.com/projects/getpids/index.html *  * @author lichengwu * @created 2012-1-18 * * @return */private static String getPIDFromOS() {String pid = null;String[] cmd = null;File tempFile = null;String osName = ParameterUtil.getParameter(Parameter.OS_NAME);// 处理windowsif (osName.toLowerCase().contains("windows")) {FileInputStream fis = null;FileOutputStream fos = null;try {// 创建临时getpids.exe文件tempFile = File.createTempFile("getpids", ".exe");File getpids = new File(ParameterUtil.getResourcePath("getpids.exe"));fis = new FileInputStream(getpids);fos = new FileOutputStream(tempFile);byte[] buf = new byte[1024];while (fis.read(buf) != -1) {fos.write(buf);}// 获得临时getpids.exe文件路径作为命令cmd = new String[] { tempFile.getAbsolutePath() };} catch (FileNotFoundException e) {log.equals(e);} catch (IOException e) {log.equals(e);} finally {if (tempFile != null) {tempFile.deleteOnExit();}Closer.close(fis, fos);}}// 处理非windowselse {cmd = new String[] { "/bin/sh", "-c", "echo $$ $PPID" };}InputStream is = null;ByteArrayOutputStream baos = null;try {byte[] buf = new byte[1024];Process exec = Runtime.getRuntime().exec(cmd);is = exec.getInputStream();baos = new ByteArrayOutputStream();while (is.read(buf) != -1) {baos.write(buf);}String ppids = baos.toString();// 对于windows参考:http://www.scheibli.com/projects/getpids/index.htmlpid = ppids.split(" ")[1];} catch (Exception e) {log.error(e);} finally {if (tempFile != null) {tempFile.deleteOnExit();}Closer.close(is, baos);}return pid;}}
1 楼 JetMah 2012-01-19   ParameterUtil? 2 楼 zk1878 2012-01-19   感觉这个String pid = System.getProperty("pid"); 
        if (pid == null) { 
不靠谱, 如果有人蛋疼的写上System.setProperty("pid","123")之类 如何看待; 3 楼 ol_beta 2012-01-19   zk1878 写道感觉这个String pid = System.getProperty("pid"); 
        if (pid == null) { 
不靠谱, 如果有人蛋疼的写上System.setProperty("pid","123")之类 如何看待;
这是为了方便下次取得pid来缓存的,当然你System.setProperty任何东西,你可以覆盖jvm的属性,版本信息,厂商...关键是,一般人都不会做。

热点排行