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:System.ConsoleHelper.java

@Override
public ArrayList<String> executeProgram(String programName) {
    System.out.println("ConsoleHelper : executing programm " + programName);

    ArrayList<String> result = new ArrayList<>();
    File dir = new File(clientID);
    Process p;
    try {//from   www .  jav  a2  s.  co  m
        p = Runtime.getRuntime().exec(programName, null, dir);

        if (!p.waitFor(timeout, TimeUnit.SECONDS)) {
            System.out.println("ConsoleHelper : timeout");
            result.add("Program timed out after " + timeout + "seconds.\nYou probably have an infinite loop.");
            //timeout
            p.destroy();
        } else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader reader_err = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
            while ((line = reader_err.readLine()) != null) {
                result.add(line);
            }
        }
    } catch (IOException ex) {
        System.err.println("ConsoleHelper : Error executing programm " + programName + " " + ex.getMessage());
    } catch (InterruptedException ex) {
        System.err.println(
                "ConsoleHelper : Error executing programm " + programName + " timeout : " + ex.getMessage());
    }
    return result;
}

From source file:net.openhft.chronicle.VanillaChronicleTestBase.java

public void lsof(final String pid, final String pattern) throws IOException {
    String cmd = null;//from w  ww  .  j  a v  a 2s. co  m
    if (new File("/usr/sbin/lsof").exists()) {
        cmd = "/usr/sbin/lsof";

    } else if (new File("/usr/bin/lsof").exists()) {
        cmd = "/usr/bin/lsof";
    }

    if (cmd != null) {
        final ProcessBuilder pb = new ProcessBuilder(cmd, "-p", pid);
        final Process proc = pb.start();
        final BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line;
        while ((line = br.readLine()) != null) {
            if (StringUtils.isBlank(pattern) || line.matches(pattern) || line.contains(pattern)) {
                System.out.println(line);
            }
        }

        br.close();
        proc.destroy();
    }
}

From source file:net.ymate.platform.core.util.RuntimeUtils.java

/**
 * ?????/*from   www  .  java  2 s. c  o m*/
 */
public static void initSystemEnvs() {
    Process p = null;
    BufferedReader br = null;
    try {
        if (SystemUtils.IS_OS_WINDOWS) {
            p = Runtime.getRuntime().exec("cmd /c set");
        } else if (SystemUtils.IS_OS_UNIX) {
            p = Runtime.getRuntime().exec("/bin/sh -c set");
        } else {
            _LOG.warn("Unknown os.name=" + SystemUtils.OS_NAME);
            SYSTEM_ENV_MAP.clear();
        }
        if (p != null) {
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                int i = line.indexOf('=');
                if (i > -1) {
                    String key = line.substring(0, i);
                    String value = line.substring(i + 1);
                    SYSTEM_ENV_MAP.put(key, value);
                }
            }
        }
    } catch (IOException e) {
        _LOG.warn(RuntimeUtils.unwrapThrow(e));
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                _LOG.warn("", e);
            }
        }
        if (p != null) {
            p.destroy();
        }
    }
}

From source file:com.mobiperf.speedometer.measurements.PingTask.java

private void cleanUp(Process proc) {
    try {//  w ww.  ja v a2  s  .  c o  m
        if (proc != null) {
            proc.destroy();
        }
    } catch (Exception e) {
        Logger.w("Unable to kill ping process", e);
    }
}

From source file:io.fabric8.kit.common.ExternalCommand.java

public void execute(String processInput) throws IOException {
    final Process process = startProcess();
    start();//  ww  w. j a  v  a2  s  .  c  om
    try {
        inputStreamPump(process.getOutputStream(), processInput);

        Future<IOException> stderrFuture = startStreamPump(process.getErrorStream());
        outputStreamPump(process.getInputStream());

        stopStreamPump(stderrFuture);
        checkProcessExit(process);
    } catch (IOException e) {
        process.destroy();
        throw e;
    } finally {
        end();
    }
    if (statusCode != 0) {
        throw new IOException(
                String.format("Process '%s' exited with status %d", getCommandAsString(), statusCode));
    }

}

From source file:oracle.CubistOracle.common.CubistOracle.java

private String _blocking_createCubistModel(String filestem) {
    try {/*w  w  w  .j a  v  a2  s. co  m*/
        String[] command = buildCommand(filestem);
        if (t)
            log.trace("Invoking " + Arrays.toString(command));
        Process p = Runtime.getRuntime().exec(buildCommand(filestem));
        p.waitFor();
        checkForError(p);
        if (cubistConfig.isPrintModelOnBuild()) {
            printOutputBuild(p);
        }
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Could not create CubistModel " + e.getMessage());
    }
    return modelString();
}

From source file:org.daisy.pipeline.execution.rmi.PoolableRMIPipelineInstanceFactory.java

private Process launchNewPipelineInstance(final String id) throws IOException {
    List<String> cmd = new ArrayList<String>();
    cmd.add(javaPath);/*w w w.j a v  a 2  s . c om*/

    // Add VM arguments
    BufferedReader br = null;
    try {
        File argFile = new File(pipelineDir, "rmi/vmargs.conf");
        if (argFile.exists()) {
            br = new BufferedReader(new FileReader(argFile));
            String line;
            while ((line = br.readLine()) != null) {
                cmd.add(line);
            }
        }
    } catch (Exception e) {
        logger.warn("Couldn't read VM arguments", e);
    } finally {
        if (br != null) {
            br.close();
        }
    }

    // Add class path
    cmd.add("-cp");
    cmd.add(buildClassPath());

    // Add application class and arguments
    cmd.add(RMIPipelineApp.class.getName());
    cmd.add(id);
    String[] cmdarray = (String[]) cmd.toArray(new String[cmd.size()]);

    if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (String item : cmdarray) {
            sb.append(item).append(' ');
        }
        logger.debug("Launching {} with cmd \"{}\"", id, sb.toString());
    }
    final Process process = Runtime.getRuntime().exec(cmdarray, null, pipelineDir);

    // Register a shutdown hook to terminate live RMI Pipeline
    // instances when the JVM quits.
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            process.destroy();
        }
    });
    return process;
}

From source file:org.zilverline.web.HandlerValidator.java

/**
 * Validator for SearchForm. Validates name, maxResults, startAt and query
 * /*from  w  w w  .j av  a 2s.  com*/
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {
    Handler handler = (Handler) obj;
    Map mappings = handler.getMappings();
    // convert the keys to lowercase
    Iterator mapping = mappings.entrySet().iterator();

    try {
        while (mapping.hasNext()) {
            Map.Entry element = (Map.Entry) mapping.next();
            String archiver = (String) element.getValue();
            log.debug("checking mappings: " + archiver);
            // can be empty: then java.util.Zip used
            if (StringUtils.hasLength(archiver)) {
                // the archiver is an external application with options,
                // check whether the application exists
                String exe = archiver.split(" ")[0];
                log.debug("checking mappings: " + exe);
                File exeFile = new File(exe);
                if (exeFile.exists()) {
                    log.debug("Can find " + exe);
                    continue;
                }

                // else try find the thing on the path
                Process proc = Runtime.getRuntime().exec(exe);
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                proc.destroy();
                log.debug("Exit value: " + proc.exitValue());

                // everthing OK?
                if (proc.exitValue() != 0) {
                    // error executing proc
                    log.debug(" --> Can't execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                    log.debug("mappings must exist on disk: " + exe);
                    errors.rejectValue("mappings", null, null, "must exist on disk.");
                } else {
                    log.debug(" --> Can execute: '" + exe + "'. Exit value: "
                            + SysUtils.getErrorTextById(proc.exitValue()));
                }
            }
        }
    } catch (Exception e) {
        log.debug("Can not execute one of the mappings", e);
        errors.rejectValue("mappings", null, null, "must exist on disk.");
    }

}

From source file:com.exalttech.trex.util.PacketUtil.java

/**
 * Run stl-sim command to generates pcap file
 *
 * @param fileName//  w w  w.  j  av a2 s  . c o m
 * @throws IOException
 * @throws InterruptedException
 */
public void generatePcapFile(String fileName) throws IOException, InterruptedException {
    String line;
    String command = STL_SIM_COMMAND.replace("[FILE_NAME]", fileName);
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while ((line = bufferReader.readLine()) != null) {
        LOG.info("line: " + line);
    }
    process.waitFor();
    process.destroy();
}

From source file:org.eclipse.kura.deployment.customizer.upgrade.rp.UpgradeScriptResourceProcessorImpl.java

private void executeScript(File file) throws Exception {
    String path = file.getCanonicalPath();
    String[] cmdarray = { "/bin/bash", path };
    Runtime rt = Runtime.getRuntime();
    Process proc = null;
    try {/*  w w  w .j  ava 2  s  .  c  o  m*/
        proc = rt.exec(cmdarray);
        if (proc.waitFor() != 0) {
            s_logger.error("Script {} failed with exit value {}", path, proc.exitValue());
        }
        // FIXME: streams must be consumed concurrently
    } catch (Exception e) {
        s_logger.error("Error executing process for script {}", path, e);
        throw e;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
    }
}