如何使用java获取linux中特定端口的进程信息

时间:2017-07-22 06:26:39

标签: java linux process

我想找到一个在端口号上运行的进程processid。之后我想使用processid杀死进程。所以这就是我尝试过的:

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

1 个答案:

答案 0 :(得分: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);
            }}