2014-05-22 1 views
2

Windows에서 실행 중입니다.Java, windows : 지정된 PID의 프로세스 이름을 가져옵니다.

내 프로그램에서 Skype와 같은 프로세스가 포트 :80에서 실행되고 있음을 알아야합니다.

나는

netstat -o -n -a | findstr 0.0:80를 통해 포트 :80에서 실행중인 프로세스의 PID를 얻을 수 있어야합니다.

Java에서 주어진 PID를 가진 프로세스의 이름을 얻는 가장 좋은 방법은 무엇입니까?

Java 내에서 포트 :80에서 실행중인 프로세스의 이름을 얻는 방법이 있다면 그 또한 선호 할 것입니다.

내가 필요한 이유는 내 응용 프로그램이 포트 :80을 사용하는 부두 웹 서버를 시작하기 때문입니다. 다른 서비스가 이미 포트 :80을 실행 중임을 사용자에게 경고하고 싶습니다.

+0

당신이 Windows 또는 Linux에서 실행하고 있습니까? –

+0

그것은 창문 위에있다. – Markus

답변

0

그래서 두 개의 프로세스를 사용하여 작업했습니다. 하나는 PID를 얻기위한 것이고 다른 하나는 이름을 얻기위한 것입니다. 여기

그것입니다

private String getPIDRunningOnPort80() { 
     String cmd = "cmd /c netstat -o -n -a | findstr 0.0:80"; 

     Runtime rt = Runtime.getRuntime(); 
     Process p = null; 
     try { 
      p = rt.exec(cmd); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     StringBuffer sbInput = new StringBuffer(); 
     BufferedReader brInput = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     BufferedReader brError = new BufferedReader(new InputStreamReader(p.getErrorStream())); 

     String line; 
     try { 
      while ((line = brError.readLine()) != null) { 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      while ((line = brInput.readLine()) != null) { 
       sbInput.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      p.waitFor(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

     p.destroy(); 

     String resultString = sbInput.toString(); 
     resultString = resultString.substring(resultString.lastIndexOf(" ", resultString.length())).replace("\n", ""); 
     return resultString; 
    } 



private String getProcessNameFromPID(String pid) { 
    Process p = null; 
    try { 
     p = Runtime.getRuntime().exec("tasklist"); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    StringBuffer sbInput = new StringBuffer(); 
    BufferedReader brInput = new BufferedReader(new InputStreamReader(p.getInputStream())); 
    String line; 
    String foundLine = "UNKNOWN"; 
    try { 
     while ((line = brInput.readLine()) != null) { 
      if (line.contains(pid)){ 
       foundLine = line; 
      } 
      System.out.println(line); 
      sbInput.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    try { 
     p.waitFor(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    p.destroy(); 

    String result = foundLine.substring(0, foundLine.indexOf(" ")); 



    return result; 
} 
관련 문제