简体   繁体   中英

How to get the process information on a specific port in linux using java

I want to find the processid of a process which is running on a port number. After that I want to kill that process using processid .So this is what I tried:

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);
         }
}

But this command is not getting executed.

So how can I get the process id of a process which is running on port 9090 ?

Try this running code i hope it will help you

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);
            }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM