All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.epam.jdi.light.common.UnixProcessUtils Maven / Gradle / Ivy

There is a newer version: 1.6.0
Show newest version
package com.epam.jdi.light.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.epam.jdi.tools.StringUtils.inputStreamToList;


public class UnixProcessUtils {
    /**
     *
     * @param rootNamePart
     */
    public static void killProcessesTree(String rootNamePart) {
        List chrome;
        try {
            chrome = getPIDsByNamePart(rootNamePart);
            for (String s : chrome) {
                int pid = Integer.parseInt(s);
                killChildProcesses(pid);
            }
            killProcessesByNamePart(rootNamePart);
        } catch (InterruptedException | IOException e) {
            throw new RuntimeException("Can't kill drivers");
        }
    }

    /**
     *
     * @param name
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    private static List getPIDsByNamePart(String name) throws IOException, InterruptedException {
        Process process = new ProcessBuilder(
            "/usr/bin/pgrep", "-afi", name)
            .start();
        process.waitFor();
        return inputStreamToList(process.getInputStream());
    }

    /**
     *
     * @param pid
     */
    private static void killChildProcesses(int pid) {
        String ppid = String.valueOf("-P "+pid);
        killProcessWithArgs(Collections.singletonList(ppid));
    }

    /**
     *
     * @param name
     */
    public static void killProcessesByNamePart(String name) {
        killProcessWithArgs(Arrays.asList("-aif", name));
    }

    /**
     *
     * @param args
     */
    private static void killProcessWithArgs(List args) {
        List list = new ArrayList<>();
        list.add("/usr/bin/pkill");
        list.addAll(args);
        try {
            Process child = new ProcessBuilder(list.toArray(new String[list.size()])).start();
            child.waitFor();
        } catch (InterruptedException | IOException e) {
            throw new RuntimeException("Can't kill process: " + e.getMessage());
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy