Thursday, 16 June 2016

Killing processes with name in Java

We can kill processes in Java using below code. In below example, all processes with names firefox, ieexplore and chrome will be killed in Linux or windows.
Remember that you will have to import below classes from org.apache.commons package



import org.apache.commons.io.IOUtils;import org.apache.commons.lang3.SystemUtils;


public static void killProcesses() {
        try {
                String [] processNames = {"firefox","iexplore","chrome"};
                for (String process : processNames) {
                    if (SystemUtils.IS_OS_LINUX) {
                        String[] cmd= {"/bin/sh",
 "-c", "ps -ef | grep -w "+
 process +" | grep -v grep | awk '/[0-9]/{print $2}' | xargs kill -9 "};

StringBuffer output = new StringBuffer();
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            List<String> result = IOUtils.readLines(p.getInputStream());
            for (String line : result) {
                System.out.println(line);
                output.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

                      
                    } else if (SystemUtils.IS_OS_WINDOWS) {
                        Runtime.getRuntime().exec("taskkill /F /IM "+ 
process +".exe");
                    }
                }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books