Java获取自身PID方法搜集: 其中如下方法在与SUN JDK兼容的虚拟机上是可以正常获取的。

第一种,来自:

http://rednaxelafx.iteye.com/blog/716918

Java标准库里常见的公有API确实是没有获取当前进程的ID的方法,有时候挺郁闷的,就是需要自己的PID。

于是有各种workaround,其中有很靠谱的通过JNI调用外部的C/C++扩展,然后调用操作系统提供的相应API去获取PID;也有些不怎么靠谱的hack。这里要介绍的就是后者之一,只在Sun JDK或兼容的JDK上有效的方法。

import java.lang.management.ManagementFactory;

import java.lang.management.RuntimeMXBean;

public class ShowOwnPID {

public static void main(String[] args) throws Exception {

int pid = getPid();

System.out.println("pid: " + pid);

//    System.in.read(); // block the program so that we can do some probing on it

Thread.sleep(10000);

}

private static int getPid() {

RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();

String name = runtime.getName(); // format: "pid@hostname"

try {

return Integer.parseInt(name.substring(0, name.indexOf('@')));

} catch (Exception e) {

return -1;

}

}

}

这PID是哪儿来的呢?先看RuntimeMXBean实例的来源,java.lang.management.ManagementFactory:  感兴趣的话,直接在http://rednaxelafx.iteye.com/blog/716918 查看吧。

第二种,未测试: http://tech.e800.com.cn/articles/2009/617/1245201766691_1.html

class JavaHowTo {

public native long getCurrentProcessId();

static {

System.loadLibrary("jni2");

}

}

public class JNIJavaHowTo {

public static void main(String[] args) {

JavaHowTo jht = new JavaHowTo();

System.out.println("Press Any key...");

java.io.BufferedReader input =

new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try { input.readLine();}

catch (Exception e) { e.printStackTrace();}

System.out.println(jht.getCurrentProcessId());

}

}

// jni2.cpp : Defines the entry point for the DLL application.

//

#include "stdafx.h"

#include

#include "JavaHowTo.h"

BOOL APIENTRY DllMain( HANDLE hModule,

DWORD ul_reason_for_call,

LPVOID lpReserved

)

{

return TRUE;

}

JNIEXPORT jlong JNICALL Java_JavaHowTo_getCurrentProcessId

(JNIEnv *, jobject) {

// return GetCurrentProcessId();

return getpid();

}

第三种方法,http://momy.blogbus.com/logs/29634629.html

简单思路:先生成一个能够获取PID的脚本文件,然后执行。从执行的结果中找到进程名,根据进程名获得PID,然后根据PID杀掉进程。

import java.io.BufferedReader;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.StringTokenizer;

public class KillProcess {

/**

* @param args

*/

public static void main(String[] args) {

try {

killByAppName("notepad.exe");

} catch (IOException e) {

e.printStackTrace();

}

}

public static void killByAppName(String applicationName) throws IOException {

String path = System.getProperty("user.dir");

path = "C:\\";

System.out.println(path);

final File createFileName = new File(path + "\\scriptName.vbe");

if (createFileName.exists()) {

if (createFileName.delete()) {

}

} else {

if (createFileName.createNewFile()) {

}

}

final PrintWriter pw = new PrintWriter(new FileWriter(createFileName, true), true);

pw.println("for each ps in getobject(\"winmgmts:\\\\.\\root\\cimv2:win32_process\").instances_");

pw.println("wscript.echo ps.handle&vbtab&ps.name");

pw.println("next");

pw.close();

final InputStream ii = Runtime.getRuntime().exec("cscript " + path + "\\scriptName.vbe").getInputStream();

final InputStreamReader ir = new InputStreamReader(ii);

final BufferedReader br = new BufferedReader(ir);

String str = null;

StringTokenizer st2 = null;

String pid = null;

while ((str = br.readLine()) != null) {

if (str.indexOf(applicationName) > 0) {

st2 = new StringTokenizer(str);

st2.hasMoreTokens();

pid = st2.nextToken();

System.out.println(pid);

killByPID(pid);

}

}

try {

ir.close();

ii.close();

br.close();

createFileName.delete();

} catch (final IOException e) {

e.printStackTrace();

}

}

public static void killByPID(String pid) throws IOException {

final String[] cmdArray = { "ntsd.exe", "-c", "q", "-p", pid };

final String[] cmdArray1 = { "taskkill.exe", "/PID", pid, "/T", "/F" };

int result = 0;

try {

Process process = Runtime.getRuntime().exec(cmdArray1);

process.waitFor();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

if (result != 0) {

try {

Process process = Runtime.getRuntime().exec(cmdArray);

process.waitFor();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

下面这个是英文blog上写的方法:http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html

How a Java Application Can Discover its Process ID (PID)

Occasionally it is important for an application to know its PID,specially if this application cooperates with other non-javaapplications. Currently there is no direct support for retrieving anapplication's process id by using standard Java api (this might changein the future if RFEs like

4250622,

4244896 or

4890847 are resolved).

I found five ways how to get the PID from my Java code:

Using the java management and monitoring API (java.lang.management): ManagementFactory.getRuntimeMXBean().getName(); returns something like: 28906@localhost where 28906 is the PID of JVM's process, which is in fact the PID of my app.

This hack is JVM dependent and I tested it only with Sun's JVM.

From Javadocs for getName() method of RuntimeMXBean:

Returns the name representing the running Java virtualmachine. The returned name string can be any arbitrary string and aJava virtual machine implementation can choose to embedplatform-specific useful information in the returned name string. Eachrunning virtual machine could have a different name. So even though this approach is the most comfortable one, your app can break if the implementation of this method changes.

Using shell script in addition to Java propertiesStart your app with a shellscript like this: exec java -Dpid=$$ -jar /Applications/bsh-2.0b4.jar then in java code call: System.getProperty("pid");

Using shell script's $! facility as described on this blog - this approach is fine if all you want is to create a pid file.

Using Java Native Interface (JNI) - a very cumbersome and platform dependent solution.

Using $PPID and Runtime.exec(String[]) method - described in detail in this post import java.io.IOException;

public class Pid {

public static void main(String[] args) throws IOException {

byte[] bo = new byte[100];

String[] cmd = {"bash", "-c", "echo $PPID"};

Process p = Runtime.getRuntime().exec(cmd);

p.getInputStream().read(bo);

System.out.println(new String(bo));

}

} It must be said that none of these approaches is perfect and each of them has some drawbacks.

I know that one of Sun's main priorities for Java is cross-platformcompatibility, but I have to agree with the comments on the RFEs abovewhich support the addition of a getPid() method to JDK. I especiallylike this one:

Come on Sun, this started 4.5 years ago. Give us the PID. We need it. We want it. We demand it. And another thing ... you will save a lot of developers a lot of time currently spent searching through the documentation trying to find a getPID method that isn't there! Posted by Rarb@GB on 05-MAR-2004

java 自己的 pid_Java获取自身PID方法搜集相关推荐

  1. Java绝对/相对路径获取与getResourceAsStream()方法

    原文地址:https://blog.csdn.net/zmx729618/article/details/51144588 Java路径 Java中使用的路径,分为两种:绝对路径和相对路径.具体而言, ...

  2. java中servletcontext_java中获取ServletContext常见方法

    1.在javax.servlet.Filter中直接获取 ServletContext context = config.getServletContext(); 2.在HttpServlet中直接获 ...

  3. java从键盘获取数据_java实现从键盘获取数据的方法

    java实现从键盘获取数据的方法 发布时间:2020-06-25 15:42:06 来源:亿速云 阅读:83 作者:Leah 这期内容当中小编将会给大家带来有关java实现从键盘获取数据的方法,文章内 ...

  4. c# typescript_在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法

    c# typescript by Leonardo Carreiro 莱昂纳多·卡雷罗(Leonardo Carreiro) 在任何IDE中从C#,Java或Python代码获取TypeScript接 ...

  5. 关于Java 获取时间戳的方法,我和同事争论了半天

    欢迎关注方志朋的博客,回复"666"获面试宝典 Java有两个取时间戳的方法:System.currentTimeMillis() 和 System.nanoTime(),它们的使 ...

  6. java 获取类方法_Java之反射机制三:获取类的方法

    一.实体类BigDog.java package reflex; public class BigDog extends Dog { private Integer age; public Strin ...

  7. java 取数组的前90位_java 从int数组中获取最大数的方法

    java 从int数组中获取最大数的方法 首先要有数组的概念吧,知道什么是数组,简单讲就是存放一组数据的一个组合,就是一个数组....哈哈 已知一个int数组, 编程从数组中获取最大数. 思路分析: ...

  8. java 获取调用者方法_java获取调用当前方法的方法名和行数

    java获取调用当前方法的方法名和行数 String className = Thread.currentThread().getStackTrace()[2].getClassName();//调用 ...

  9. java获取当月1号 的时间chuo_java获取时间戳的方法

    JAVA 获取当前月的初始时间的时间戳 public static long getMonthFirstDay() { Calendar calendar = Calendar.getInstance ...

最新文章

  1. R3抹掉加载的DLL
  2. 小翔和泰拉瑞亚(线段树+思维)
  3. 2018-2019-2 20175235 实验四《Android开发基础》实验报告
  4. .NET 6新特性试用 | HTTP日志记录middleware
  5. Oracle中group by用法
  6. 百度人脸识别技术应用004---利用百度云离线SDK例子程序百度在线人脸库人脸识别接口_实现在线人脸识别
  7. 查看jdk版本号和安装目录
  8. 使用3CDaemon 进行ftp 传输文件 (linux-开发板) 的方法
  9. Radasm 配置goasm
  10. Qt Designer简介
  11. Linux命令之top命令
  12. 体系结构13_Tomasulo算法
  13. 宝来客:结婚率创新低,黄金珠宝销售受影响
  14. YOUChain有链与朗新天霁共建区块链职信数字资产平台
  15. FOR ALL ENTRIES IN
  16. 移动硬盘损坏如何恢复数据
  17. vue里 a(){} 和a:()=>{}的区别
  18. 计算机毕业设计-基于微信小程序高校学生课堂扫码考勤签到系统-校园考勤打卡签到小程序
  19. 云计算大会超融合论坛分享
  20. Chrome浏览器首页被hao123劫持的解决办法

热门文章

  1. HDU1228 A + B【map】
  2. Dijkstra算法的C语言程序
  3. I00030 Grades conversion
  4. windows 常见环境变量(%AppData%、%TEMP%、%TMP%)
  5. 强悍的命令行 —— 磁盘空间的查看与磁盘空间的释放
  6. Spark 机器学习 —— 从决策树到随机森林
  7. C++ 设计模式 —— 策略模式(Strategy)
  8. “表达式必须包含 bool 类型(或可转换为 bool)”
  9. php使用 js格式解析,JavaScript解析JSON格式数据的方法示例
  10. python可以给你干什么-Python到底可以做什么?