Example usage for java.lang Process destroy

List of usage examples for java.lang Process destroy

Introduction

In this page you can find the example usage for java.lang Process destroy.

Prototype

public abstract void destroy();

Source Link

Document

Kills the process.

Usage

From source file:io.jmnarloch.cd.go.plugin.gradle.GradleTaskExecutor.java

/**
 * Executes the actual Gradle build./*from www  . jav a  2  s.  c  o  m*/
 *
 * @param builder the process builder
 * @param console the log output
 * @return the process return value
 * @throws IOException          if any error occurs during I/O operation
 * @throws InterruptedException if any error occurs during process execution
 */
private static int execute(ProcessBuilder builder, JobConsoleLogger console)
        throws IOException, InterruptedException {

    Process process = null;
    try {
        process = builder.start();

        console.readOutputOf(process.getInputStream());
        console.readErrorOf(process.getErrorStream());
        return process.waitFor();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:com.ms.commons.standalone.utils.Shell.java

public static String exec(String cmd) {
    Process process = null;
    String[] cmds = { "/bin/bash", "-c", cmd, };
    try {//from w  ww . ja  v a2s. c o  m
        process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
        byte[] buffer = IOUtils.toByteArray(process.getInputStream());
        process.waitFor();
        return new String(buffer, "utf-8");
    } catch (Exception e) {
        logger.error("runtime.exec cmd: " + cmd + " failed", e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return "";
}

From source file:Main.java

public static boolean runWithRoot(String command) {
    int result = -1;

    Process process = null;
    DataOutputStream os = null;/*w  ww.j  a  v a  2s  .  c o  m*/
    try {
        process = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command + "\n");
        os.writeBytes("exit\n");
        os.flush();
        result = process.waitFor();
    } catch (Exception e) {
        return false;
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    return result == 1;
}

From source file:Main.java

public static String getBusyBoxVer() {
    String text = "";
    Process process = null;
    try {//from w  w w. j  av a 2  s.  co m
        //Execute command.
        process = Runtime.getRuntime().exec("busybox");

        //Read file (one line is enough).
        text = readFile(process.getInputStream(), 1);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    if (!TextUtils.isEmpty(text)) {
        //Like this:
        //BusyBox v1.22.1 bionic (2015-05-25 18:22 +0800) multi-call binary.
        String[] infos = text.split(" ");
        if (infos[0].equalsIgnoreCase("busybox")) {
            if (infos[1].startsWith("v") || infos[1].startsWith("V")) {
                return infos[1].substring(1);
            }
        }
    }

    return "";
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*ww  w .j a  v  a2  s  .  c o m*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:org.arquillian.cube.kubernetes.impl.utils.ProcessUtil.java

private static void addShutdownHook(final Logger log, final Process process, final String command) {
    Runtime.getRuntime().addShutdownHook(new Thread(command) {
        @Override/*from   www  .j av  a 2 s.  co m*/
        public void run() {
            if (process != null) {
                log.info("Terminating process [" + command + "]");
                try {
                    process.destroy();
                } catch (Exception e) {
                    log.error("Failed to terminate process [" + command + "]");
                }
            }
        }
    });
}

From source file:com.tafayor.selfcamerashot.utils.Util.java

public static boolean isRooted() {

    // Method 1//from w  w w  .  j av a2s  . com
    //--------------
    String[] paths = { "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su",
            "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/bin/su",
            "/xbin/su", "/sbin/su", };

    for (String path : paths) {
        if (new File(path).exists())
            return true;
    }

    // Method 2
    //--------------

    Process process = null;
    try {
        process = Runtime.getRuntime().exec(new String[] { "which", "su" });
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        if (in.readLine() != null) {
            return true;
        }
        return false;
    } catch (Throwable t) {
        return false;
    } finally {
        if (process != null)
            process.destroy();
    }

}

From source file:org.b3log.latke.util.Execs.java

/**
 * Executes the specified command.//from w ww  .j a v a2s  .  com
 *
 * @param cmd the specified command
 * @return execution output, returns {@code null} if execution failed
 */
public static String exec(final String cmd) {
    InputStream inputStream = null;

    try {
        final Process p = Runtime.getRuntime().exec(cmd);

        // Starts a thread for error stream
        final Thread t = new Thread(new InputStreamRunnable(p.getErrorStream()));

        t.start();

        inputStream = p.getInputStream();
        final String result = IOUtils.toString(inputStream, "UTF-8");

        inputStream.close();
        p.destroy();

        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "Executes command [" + cmd + "] failed", e);

        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.b3log.latke.util.Execs.java

/**
 * Executes the specified commands./*from   w  w w  .  j  ava2  s.c om*/
 *
 * @param cmds the specified commands
 * @return execution output, returns {@code null} if execution failed
 */
public static String exec(final String[] cmds) {
    InputStream inputStream = null;

    try {
        final Process p = Runtime.getRuntime().exec(cmds);

        // Starts a thread for error stream
        final Thread t = new Thread(new InputStreamRunnable(p.getErrorStream()));

        t.start();

        inputStream = p.getInputStream();
        final String result = IOUtils.toString(inputStream, "UTF-8");

        inputStream.close();
        p.destroy();

        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "Executes commands [" + Arrays.toString(cmds) + "] failed", e);

        return null;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.apache.geode.management.internal.cli.util.MergeLogs.java

public static void mergeLogsInNewProcess(Path logDirectory) {
    // create a new process for merging
    LogWrapper.getInstance().fine("Exporting logs merging logs" + logDirectory);
    List<String> commandList = new ArrayList<String>();
    commandList.add(System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java");
    commandList.add("-classpath");
    commandList.add(System.getProperty("java.class.path", "."));
    commandList.add(MergeLogs.class.getName());

    commandList.add(logDirectory.toAbsolutePath().toString());

    ProcessBuilder procBuilder = new ProcessBuilder(commandList);
    StringBuilder output = new StringBuilder();
    String errorString = new String();
    try {/*from   w w  w  . ja va2 s. c  o m*/
        LogWrapper.getInstance().fine("Exporting logs now merging logs");
        Process mergeProcess = procBuilder.redirectErrorStream(true).start();

        mergeProcess.waitFor();

        InputStream inputStream = mergeProcess.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        while ((line = br.readLine()) != null) {
            output.append(line).append(GfshParser.LINE_SEPARATOR);
        }
        mergeProcess.destroy();
    } catch (Exception e) {
        LogWrapper.getInstance().severe(e.getMessage());
    }
    if (output.toString().contains("Merged logs to: ")) {
        LogWrapper.getInstance().fine("Exporting logs Sucessfully merged logs");
    } else {
        LogWrapper.getInstance().severe("Could not merge");
    }
}