程式扎記: [ Java 常見問題 ] How to get PID from Process in Java

標籤

2014年9月16日 星期二

[ Java 常見問題 ] How to get PID from Process in Java

Source From Here 
Preface 
A node from http://bugs.sun.com/view_bug.do?bug_id=4244896 

How 
On Linux: 
  1. if(process.getClass().getName().equals("java.lang.UNIXProcess")) {  
  2.   /* get the PID on unix/linux systems */  
  3.   try {  
  4.     Field f = process.getClass().getDeclaredField("pid");  
  5.     f.setAccessible(true);  
  6.     pid = f.getInt(p);  
  7.   } catch (Throwable e) {  
  8.   }  
  9. }  
On Windows: 
Download the jna.jar on Suns JNA Site: 
  1. if (process.getClass().getName().equals("java.lang.Win32Process") ||  
  2.        process.getClass().getName().equals("java.lang.ProcessImpl")) {  
  3.   /* determine the pid on windows plattforms */  
  4.   try {  
  5.     Field f = p.getClass().getDeclaredField("handle");  
  6.     f.setAccessible(true);                
  7.     long handl = f.getLong(p);  
  8.       
  9.     Kernel32 kernel = Kernel32.INSTANCE;  
  10.     W32API.HANDLE handle = new W32API.HANDLE();  
  11.     handle.setPointer(Pointer.createConstant(handl));  
  12.     pid = kernel.GetProcessId(handle);  
  13.   } catch (Throwable e) {                 
  14.   }  
  15. }  

Supplement 
Stackoferflow - How to execute a interactive shell script using java Runtime?

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!