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:Main.java

public static String getLocalDns(String dns) {
    Process process = null;
    String str = "";
    BufferedReader reader = null;
    try {/* w  w  w . jav  a 2 s . c o  m*/
        process = Runtime.getRuntime().exec("getprop net." + dns);
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            str += line;
        }
        reader.close();
        process.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            process.destroy();
        } catch (Exception e) {
        }
    }
    return str.trim();
}

From source file:com.clustercontrol.platform.PlatformPertial.java

public static void setupHostname() {
    String hostname = null;//from  w  ww  .j  ava 2 s  .  co  m
    // hinemos.cfg???hostname?
    String etcDir = System.getProperty("hinemos.manager.etc.dir");
    if (etcDir != null) {
        File config = new File(etcDir, "hinemos.cfg");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(config.getAbsolutePath());
            br = new BufferedReader(fr);

            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.trim().startsWith("MANAGER_HOST")) {
                    hostname = line.split("=")[1];
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            log.warn("configuration file not found." + config.getAbsolutePath(), e);
        } catch (IOException e) {
            log.warn("configuration read error." + config.getAbsolutePath(), e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null || hostname.length() == 0) {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        InputStreamReader is = null;
        BufferedReader br = null;

        try {
            process = runtime.exec("hostname");

            is = new InputStreamReader(process.getInputStream());
            br = new BufferedReader(is);
            process.waitFor();

            if (br != null) {
                hostname = br.readLine();
            }

        } catch (IOException | InterruptedException e) {
            log.warn("command execute error.", e);
        } finally {
            if (process != null) {
                process.destroy();
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null) {
        hostname = "";
    }

    System.setProperty("hinemos.manager.hostname", hostname);
}

From source file:org.adl.util.EnvironmentVariable.java

/**
 * Retrieves the value of the specified environment variable.
 *
 * @param iKey   Name of the environment variable.
 *
 * @return Value of the specified environment variable.
 *//*w w  w .j  a va 2  s.  c  om*/
public static String getValue(String iKey) {
    String value = "";

    try {
        Process p;
        String osName = System.getProperty("os.name");

        if ((osName.equalsIgnoreCase("Windows 95")) || (osName.equalsIgnoreCase("Windows 98"))
                || (osName.equalsIgnoreCase("Windows Me"))) {
            p = Runtime.getRuntime().exec("command.com /c echo %" + iKey + "%");
        } else {
            p = Runtime.getRuntime().exec("cmd.exe /c echo %" + iKey + "%");
        }

        p.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        value = br.readLine();

        if (StringUtils.startsWith(value, "%")) {
            value = "";
        }

        br.close();
        p.destroy();
    } catch (IOException ioe) {
        System.out.println("Could not read environment variable key " + iKey);
    } catch (InterruptedException ie) {
        System.out.println("The process has been interrupted");
    }

    return value;
}

From source file:org.rapidcontext.app.plugin.cmdline.CmdLineExecProcedure.java

/**
 * Waits for the specified process to terminate, reading its
 * standard output and error streams meanwhile.
 *
 * @param process        the process to monitor
 * @param cx             the procedure call context
 *
 * @return the data object with the process output results
 *
 * @throws IOException if the stream reading failed
 */// www .ja v a  2 s .  com
private static Dict waitFor(Process process, CallContext cx) throws IOException {

    StringBuffer output = new StringBuffer();
    StringBuffer error = new StringBuffer();
    InputStream isOut = process.getInputStream();
    InputStream isErr = process.getErrorStream();
    byte[] buffer = new byte[4096];
    int exitValue = 0;
    process.getOutputStream().close();
    while (true) {
        if (cx.isInterrupted()) {
            // TODO: isOut.close();
            // TODO: isErr.close();
            process.destroy();
            throw new IOException("procedure call interrupted");
        }
        try {
            readStream(isOut, buffer, output);
            readStream(isErr, buffer, error);
            log(cx, error);
            exitValue = process.exitValue();
            break;
        } catch (IllegalThreadStateException e) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException ignore) {
                // Ignore this exception
            }
        }
    }
    Dict res = new Dict();
    res.setInt("exitValue", exitValue);
    res.set("output", output);
    return res;
}

From source file:org.pentaho.reporting.designer.core.util.ExternalToolLauncher.java

public static boolean execute(final String executable, final String parameters, final String file)
        throws IOException {
    // todo: Use a stream tokenizer (well, a custom one, as the builtin one messes up escaped quotes)
    // so that we can handle quoting gracefully ..
    boolean exitValue = false;
    final ArrayList<String> command = new ArrayList<String>();
    command.add(executable);//  w  w w.  ja  v a2 s.  c o m
    for (StringTokenizer tokenizer = new StringTokenizer(parameters); tokenizer.hasMoreTokens();) {
        String s = tokenizer.nextToken();
        s = s.replace("{0}", file);
        command.add(s);
    }

    final String osname = safeSystemGetProperty("os.name", "<protected by system security>"); // NON-NLS
    if (StringUtils.startsWithIgnoreCase(osname, "Mac OS X")) // NON-NLS
    {
        logger.debug("Assuming Mac-OS X."); // NON-NLS
        if (executable.endsWith(".app") || executable.endsWith(".app/")) // NON-NLS
        {
            command.add(0, "-a"); // NON-NLS
            command.add(0, "/usr/bin/open"); // NON-NLS
        }
    }

    final ProcessBuilder processBuilder = new ProcessBuilder(command.toArray(new String[command.size()]));
    Process process = null;
    ProcessWrapper processWrapper = null;
    try {
        process = processBuilder.start();
        processWrapper = new ProcessWrapper(process);
        processWrapper.start();
        processWrapper.join(timeout);
        if (processWrapper.getfExitCode() != null) {
            exitValue = processWrapper.getfExitCode() == 0;
        } else {
            // Set our exit code to 1
            exitValue = false;
            process.destroy();
        }
        //final Process p = process.start();
        //p.waitFor();
        //exitValue = p.exitValue() == 0;
        // 0 == normal; 2 == permissions issue, 3 == no rules found in mimeType
        logger.debug("ProcessWrapper exitCode = " + processWrapper.getfExitCode());
    } catch (InterruptedException ie) {
        processWrapper.interrupt();
        Thread.currentThread().interrupt();
        process.destroy();
        exitValue = false;
    } catch (Exception e) {
        logger.error("Error in execute shell command " + command + " error: " + e.getMessage());
        // process fails so redirect to openURL command to locate viewer
        exitValue = false;
    }
    return exitValue;
}

From source file:org.scribble.cli.ExecUtil.java

/**
 * Runs a process, up to a certain timeout,
 * //from www  . j  a v  a  2s.  c o  m
 * @throws IOException
 * @throws TimeoutException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public static ProcessSummary execUntil(Map<String, String> env, long timeout, String... command)
        throws IOException, InterruptedException, ExecutionException {
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.environment().putAll(env);
    Process process = builder.start();
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    CyclicBarrier onStart = new CyclicBarrier(3);
    Future<String> stderr = executorService.submit(toString(process.getErrorStream(), onStart));
    Future<String> stdout = executorService.submit(toString(process.getInputStream(), onStart));
    Future<Integer> waitFor = executorService.submit(waitFor(process, onStart));
    ProcessSummary result = null;
    try {
        waitFor.get(timeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        // timeouts are ok
    } finally {
        process.destroy();
        waitFor.get();
        result = new ProcessSummary(stdout.get(), stderr.get(), process.exitValue());
        executorService.shutdown();
    }
    return result;
}

From source file:net.pickapack.io.cmd.CommandLineHelper.java

/**
 *
 * @param cmd/*from  w ww .  java 2s. c o  m*/
 * @return
 */
public static List<String> invokeNativeCommandAndGetResult(String[] cmd) {
    List<String> outputList = new ArrayList<String>();

    try {
        Runtime r = Runtime.getRuntime();
        Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            pb.redirectErrorStream(true);
        //            Process ps = pb.start();

        BufferedReader rdr = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        String in = rdr.readLine();
        while (in != null) {
            outputList.add(in);
            in = rdr.readLine();
        }

        int exitValue = ps.waitFor();
        if (exitValue != 0) {
            System.out.println("WARN: Process exits with non-zero code: " + exitValue);
        }

        ps.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return outputList;
}

From source file:org.apache.spark.network.util.JavaUtils.java

private static void deleteRecursivelyUsingUnixNative(File file) throws IOException {
    ProcessBuilder builder = new ProcessBuilder("rm", "-rf", file.getAbsolutePath());
    Process process = null;
    int exitCode = -1;

    try {//  w w  w  .  ja  va2  s.  c om
        // In order to avoid deadlocks, consume the stdout (and stderr) of the process
        builder.redirectErrorStream(true);
        builder.redirectOutput(new File("/dev/null"));

        process = builder.start();

        exitCode = process.waitFor();
    } catch (Exception e) {
        throw new IOException("Failed to delete: " + file.getAbsolutePath(), e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    if (exitCode != 0 || file.exists()) {
        throw new IOException("Failed to delete: " + file.getAbsolutePath());
    }
}

From source file:jp.co.tis.gsp.tools.dba.util.ProcessUtil.java

public static void exec(Map<String, String> environment, String... args)
        throws IOException, InterruptedException {

    Process process = null;
    InputStream stdout = null;/* w  ww.  jav  a2s.  co m*/
    BufferedReader br = null;

    try {
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.redirectErrorStream(true);
        if (environment != null) {
            pb.environment().putAll(environment);
        }

        process = pb.start();
        stdout = process.getInputStream();
        br = new BufferedReader(new InputStreamReader(stdout));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(stdout);

        if (process != null) {
            process.destroy();
        }
    }
}

From source file:org.springframework.integration.gemfire.fork.ForkUtil.java

public static OutputStream cloneJVM(String argument) {
    String cp = System.getProperty("java.class.path");
    String home = System.getProperty("java.home");

    Process proc = null;/*from  w  ww.  j a va 2 s.c om*/
    String java = home + "/bin/java".replace("\\", "/");

    String argClass = argument;

    String[] cmdArray = { java, "-cp", cp, argClass };
    try {
        // ProcessBuilder builder = new ProcessBuilder(cmd, argCp,
        // argClass);
        // builder.redirectErrorStream(true);
        proc = Runtime.getRuntime().exec(cmdArray);
    } catch (IOException ioe) {
        throw new IllegalStateException("Cannot start command " + cmdArray, ioe);
    }

    logger.info("Started fork");
    final Process p = proc;

    final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    final BufferedReader ebr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    final AtomicBoolean run = new AtomicBoolean(true);

    Thread reader = copyStdXxx(br, run, System.out);
    Thread errReader = copyStdXxx(ebr, run, System.err);

    reader.start();
    errReader.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            logger.info("Stopping fork...");
            run.set(false);
            if (p != null) {
                p.destroy();
            }

            try {
                p.waitFor();
            } catch (InterruptedException e) {
                // ignore
            }
            logger.info("Fork stopped");
        }
    });

    return proc.getOutputStream();
}