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:com.hi.datacleaner.ExternalCommandTransformer.java

private String[] getResult(List<String> commandTokens) throws IOException, InterruptedException {
    Process process = new ProcessBuilder(commandTokens).start();

    if (!process.waitFor(_timeout, TimeUnit.MILLISECONDS)) {
        process.destroy();
        throw new InterruptedException(
                "Process has been interrupted because of timeout (" + _timeout + "ms). ");
    }/*from  w ww. j av a 2s  . c o m*/

    BufferedReader stdin = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    StringBuilder result = new StringBuilder();
    String line;
    int linesCount = 0;

    while ((line = stdin.readLine()) != null) {
        linesCount++;
        result.append(line).append(_separator);
    }

    if (linesCount == 0) {
        result.append(ERROR);

        while ((line = stderr.readLine()) != null) {
            result.append(line).append(_separator);
        }
    }

    return new String[] { result.toString() };
}

From source file:org.eclipse.swt.snippets.SnippetExplorer.java

/**
 * Test if the given command can be executed.
 *
 * @param command command to test/*from  w  w  w  .  j  a  v  a  2 s.c o  m*/
 * @return <code>false</code> if executing the command failed for any reason
 */
private static boolean canRunCommand(String command) {
    try {
        final Process p = Runtime.getRuntime().exec(command);
        p.waitFor(150, TimeUnit.MILLISECONDS);
        if (p.isAlive()) {
            p.destroy();
            p.waitFor(100, TimeUnit.MILLISECONDS);
            if (p.isAlive()) {
                p.destroyForcibly();
            }
        }
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:org.apache.sling.testing.serversetup.jarexec.ShutdownHookSingleProcessDestroyer.java

public void destroyProcess(boolean waitForIt) {
    Process toDestroy = null;
    synchronized (this) {
        toDestroy = process;//w ww.  ja  va  2 s.  co  m
        process = null;
    }

    if (toDestroy == null) {
        return;
    }

    toDestroy.destroy();

    if (waitForIt) {
        log.info("Waiting for destroyed process {} to exit (timeout={} seconds)", processInfo, timeoutSeconds);
        final Thread mainThread = Thread.currentThread();
        final Timer t = new Timer(true);
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                mainThread.interrupt();
            }
        };
        t.schedule(task, timeoutSeconds * 1000L);
        try {
            toDestroy.waitFor();
            try {
                final int exit = toDestroy.exitValue();
                log.info("Process {} ended with exit code {}", processInfo, exit);
            } catch (IllegalStateException ise) {
                log.error("Failed to destroy process " + processInfo);
            }
        } catch (InterruptedException e) {
            log.error("Timeout waiting for process " + processInfo + " to exit");
        } finally {
            t.cancel();
        }
    }
}

From source file:org.jboss.qa.jcontainer.util.executor.LoopProcessTest.java

@Test
public void loopProcessStreams() throws IOException, InterruptedException {
    final Process process = ProcessExecutor.builder().commands(commands).outputStream(System.out)
            .errorStream(System.err).redirectError(false).build().asyncExecute();
    Thread.sleep(3000);//from w  w  w  .java2s. c  om
    log.info("Terminate process");
    process.destroy();
    assertEquals(0, process.waitFor());
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *//* w  ww  . ja  va2 s  .  c  o m*/
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}

From source file:xbdd.webapp.resource.feature.PrintPDF.java

public void generatePDF(final List<String> commands) throws IOException {
    final ProcessBuilder probuilder = new ProcessBuilder(commands);
    probuilder.redirectError();//  ww w.j a  va  2 s  . co  m
    probuilder.redirectOutput();
    probuilder.redirectInput();
    final Process process = probuilder.start();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
    process.destroy();
}

From source file:edu.umd.cs.marmoset.utilities.MarmosetUtilities.java

/**
 * Uses the kill command to kill this process as a group leader with: <br>
 * kill -9 -&lt;pid&gt;//  w ww  .j  av a 2  s. c o m
 * <p>
 * If kill -9 -&lt;pid&gt; fails, then this method will call
 * @param process
 */
public static void destroyProcessGroup(Process process, Logger log) {
    int pid = 0;
    try {
        pid = getPid(process);

        log.debug("PID to be killed = " + pid);

        //String command = "kill -9 -" +pid;
        String command = "kill -9 " + pid;

        String[] cmd = command.split("\\s+");

        Process kill = Runtime.getRuntime().exec(cmd);
        log.warn("Trying to kill the process group leader: " + command);
        kill.waitFor();
    } catch (IOException e) {
        // if we can't execute the kill command, then try to destroy the process
        log.warn("Unable to execute kill -9 -" + pid + "; now calling process.destroy()");
    } catch (InterruptedException e) {
        log.error("kill -9 -" + pid + " process was interrupted!  Now calling process.destroy()");
    } finally {
        // call process.destroy() whether or not "kill -9 -<pid>" worked
        // in order to maintain proper internal state
        process.destroy();
    }
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Destroy given process.//from   ww w.ja v a  2s . c om
 * @param process
 */
private void destroyProcess(Process process) {
    if (process != null) {
        try {
            process.destroy();
        } catch (Exception e) {
            log.trace("Error destroying process", e);
        }
    }
}

From source file:com.searchcode.app.util.Helpers.java

public void closeQuietly(Process process) {
    try {// w  w w  .j a v  a 2  s  .  com
        process.destroy();
    } catch (Exception ex) {
    }
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

protected static String runProcess(String[] commandLine) throws IOException {
    StringBuilder cl = new StringBuilder();
    for (String i : commandLine) {
        cl.append(i);/*  w w w .  ja  v  a 2s .  c  o  m*/
        cl.append(" ");
    }

    String result = "";

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    Map<String, String> env = builder.environment();
    env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
    builder.redirectErrorStream(true);
    Process process = builder.start();

    String line;

    InputStream stdout = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }

    boolean isProcessRunning = true;
    int maxRetries = 60;

    do {
        try {
            isProcessRunning = process.exitValue() < 0;
        } catch (IllegalThreadStateException ex) {
            System.out.println("Process not terminated. Waiting ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException iex) {
                //nothing todo
            }
            maxRetries--;
        }
    } while (isProcessRunning && maxRetries > 0);
    System.out.println("Process has terminated");
    if (process.exitValue() != 0) {
        throw new IllegalStateException("Exit value not equal to 0: " + result);
    }
    if (maxRetries == 0 && isProcessRunning) {
        System.out.println("Process does not terminate. Try to kill the process now.");
        process.destroy();
    }

    return result;
}