java 自己的 pid_获取JAVA当前进程PID的两种方法

之前并不知道Java中如何能够获取当前进程(也就是包含当前Java程序的JVM所在进程)的进程ID,还以为要通过JNI或者通过Runtime.exec执行shell命令等方式才能获取到当前进程的进程ID,今天在偶然中看到一种在Java程序里,获取当前进程ID的方法,记录下来,以后应该会用到:)

首先,从JDK1.5之后,Java开始提供包:java.lang.management

java.lang.management 提供了一系列的用来在运行时管理和监督JVM和OS的管理接口。

今天我将用到的就是这个包中的一个类:ManagementFactory。

获取pid的程序代码如下:

importsun.management.ManagementFactory;

// get name representing the running Java virtual machine.

String name = ManagementFactory.getRuntimeMXBean().getName();

System.out.println(name);

// get pid

String pid = name.split("@")[0];

System.out.println(“Pid is:” + pid);

输出的结果如下:

25107@abc.mmm.xxx.yyy.com

Pid is :25107

第一行打印的是代表运行时JVM的一个名字,我们可以看到,这个名字是以进程pid开头,以机器名结尾,中间用“@”连接而成的。

因此我们就可以从这个名字当中,截取出我们所需的pid了。

当然,这只是java.lang.management包中的一个小功能,该包还提供了很多其他的管理接口,参照Javadoc如下:

Interface Summary

The management interface for the class loading system of the Java virtual machine.

The management interface for the compilation system of the Java virtual machine.

The management interface for the garbage collection of the Java virtual machine.

The management interface for a memory manager.

The management interface for the memory system of the Java virtual machine.

The management interface for a memory pool.

The management interface for the operating system on which the Java virtual machine is running.

The management interface for the runtime system of the Java virtual machine.

The management interface for the thread system of the Java virtual machine.

第二种方法:解析JPS命令

private static String getPid() throws IOException {

Process p = Runtime.getRuntime().exec("/home/kent/opt/jdk1.6.0_41/bin/jps");

InputStream in = p.getInputStream();

List jpsLines = IOUtils.readLines(in);

IOUtils.closeQuietly(in);

for (String line : jpsLines) {

if (line.contains(HelloPoolSize.class.getSimpleName())) {

return line.split("\\s")[0];

}

}

throw new IllegalStateException("拿不到pid");

}

这种方式可以获取到本身以外的pid ,只要改一下类HelloPoolSize.class就可以了!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值