2017-07-22 81 views
0

我想查找在端口號上運行的進程processid。從那以後,我要殺死過程使用processid。所以這是我的嘗試:如何使用java在linux中獲取特定端口上的進程信息

else if(OS.contains("linux")){ 
    try{ 
     JOptionPane.showMessageDialog(null, "in linux "); 
     Runtime rt = Runtime.getRuntime(); 
     Process proc = rt.exec("sudo netstat -nlp | grep :9090"); 

     BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream())); 
     String s = null; 
     StringBuilder sb=new StringBuilder(); 
     while ((s = stdInput.readLine()) != null) { 
      sb.append(s); 
      System.out.println(s); 
     } 
} 

但沒有得到執行這條命令。

那麼我怎麼能得到process id進程這是運行在端口9090

回答

0

試試這個運行的代碼,我希望它會幫助你

else if (OS.contains("linux")) { 
     try { 

      Runtime rt = Runtime.getRuntime(); 
      Process proc = rt.exec("netstat -nlp | grep :9090"); 

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
      String s = null; 
      StringBuilder sb = new StringBuilder(); 
      String sc = null; 
      while ((s = stdInput.readLine()) != null) { 
       if (s.contains("9090")) { 
        sb.append(s); 
        System.out.println(s); 

        String process = s.trim(); 
        int index = process.lastIndexOf(" "); 
        int to = process.indexOf("/"); 

        sc = s.substring(index, to); 

       } 

       rt.exec("kill -9 " + sc); 
      }} 
相關問題