Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

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

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:Exec.java

static Process execUnix(String[] cmdarray, String[] envp, File directory) throws IOException {
    // instead of calling command directly, we'll call the shell to change
    // directory and set environment variables.

    // start constructing the sh command line.
    StringBuffer buf = new StringBuffer();

    if (directory != null) {
        // change to directory
        buf.append("cd '");
        buf.append(escapeQuote(directory.toString()));
        buf.append("'; ");
    }/* w w w.  ja  v a 2s  . c  o m*/

    if (envp != null) {
        // set environment variables.  Quote the value (but not the name).
        for (int i = 0; i < envp.length; ++i) {
            String nameval = envp[i];
            int equals = nameval.indexOf('=');
            if (equals == -1)
                throw new IOException("environment variable '" + nameval + "' should have form NAME=VALUE");
            buf.append(nameval.substring(0, equals + 1));
            buf.append('\'');
            buf.append(escapeQuote(nameval.substring(equals + 1)));
            buf.append("\' ");
        }
    }

    // now that we have the directory and environment, run "which" 
    // to test if the command name is found somewhere in the path.
    // If "which" fails, throw an IOException.
    String cmdname = escapeQuote(cmdarray[0]);
    Runtime rt = Runtime.getRuntime();
    String[] sharray = new String[] { "sh", "-c", buf.toString() + " which \'" + cmdname + "\'" };
    Process which = rt.exec(sharray);
    try {
        which.waitFor();
    } catch (InterruptedException e) {
        throw new IOException("interrupted");
    }

    if (which.exitValue() != 0)
        throw new IOException("can't execute " + cmdname + ": bad command or filename");

    // finish in 
    buf.append("exec \'");
    buf.append(cmdname);
    buf.append("\' ");

    // quote each argument in the command
    for (int i = 1; i < cmdarray.length; ++i) {
        buf.append('\'');
        buf.append(escapeQuote(cmdarray[i]));
        buf.append("\' ");
    }

    System.out.println("executing " + buf);
    sharray[2] = buf.toString();
    return rt.exec(sharray);
}

From source file:org.mskcc.cbio.portal.util.IGVLinking.java

private static void execute(String command) throws Exception {
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();//  w ww.j av  a  2s  .com
    if (process.exitValue() != 0)
        throw new RuntimeException();
}

From source file:com.streamsets.datacollector.util.SystemProcessImpl.java

/**
 * Java 1.7 does not have Process.isAlive
 */// w  w w .  j a  v a2 s .  c  om
private static boolean isAlive(Process process) {
    try {
        process.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:ca.osmcanada.osvuploadr.Utils.Helper.java

private static boolean runCommand(String command, String args, String file) {

    logOut("Trying to exec:\n   cmd = " + command + "\n   args = " + args + "\n   %s = " + file);

    String[] parts = prepareCommand(command, args, file);

    try {//  ww  w .jav a2  s.  c o  m
        Process p = Runtime.getRuntime().exec(parts);
        if (p == null)
            return false;

        try {
            int retval = p.exitValue();
            if (retval == 0) {
                logOut("Process ended immediately.");
                return false;
            } else {
                logOut("Process crashed.");
                return false;
            }
        } catch (IllegalThreadStateException itse) {
            logOut("Process is running.");
            return true;
        }
    } catch (IOException e) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, e);
        return false;
    }
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {/*  w  ww.ja  va2s  .c om*/
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:Main.java

private static void confirmExitValueIs(int expected, Process process) {
    // Consider if we need to add timeout logic here.
    while (true) {
        try {/*from  w w w  .j a  v  a 2  s . co  m*/
            process.waitFor();
            break;
        } catch (InterruptedException exception) {
            // do nothing, try to wait again
        }
    }

    int actual = process.exitValue();

    if (expected != actual) {
        throw new RuntimeException("Exit value of process was " + actual + " but expected " + expected);
    }
}

From source file:com.atlassian.labs.bamboo.git.edu.nyu.cs.javagit.client.cli.ProcessUtilities.java

/**
 * Waits for a process to terminate and then destroys it.
 *
 * @param p/*from   w w w .  j av a2s. co  m*/
 *          The process to wait for and destroy.
 * @return The exit value of the process. By convention, 0 indicates normal termination.
 */
public static int waitForAndDestroyProcess(Process p, IParser parser) {
    /*
     * I'm not sure this is the best way to handle waiting for a process to complete. -- jhl388
     * 06.14.2008
     */
    while (true) {
        try {
            int i = p.waitFor();
            parser.processExitCode(p.exitValue());
            p.destroy();
            return i;
        } catch (InterruptedException e) {
            // TODO: deal with this interrupted exception in a better manner. -- jhl388 06.14.2008
            continue;
        }
    }
}

From source file:Main.java

public static String exec(String cmd) {
    StringBuilder sb = new StringBuilder();
    try {/*  w  w  w  . j  av  a  2s  .  com*/
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(cmd);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        br.close();
        if (process.waitFor() != 0) {
            System.err.println("exit value = " + process.exitValue());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }/*from  w w w .j  a v  a 2 s.  com*/

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}

From source file:io.ingenieux.lambda.shell.LambdaShell.java

private static void runCommandArray(OutputStream os, String... args) throws Exception {
    PrintWriter pw = new PrintWriter(os, true);

    File tempPath = File.createTempFile("tmp-", ".sh");

    IOUtils.write(StringUtils.join(args, " "), new FileOutputStream(tempPath));

    List<String> processArgs = new ArrayList<>(Arrays.asList("/bin/bash", "-x", tempPath.getAbsolutePath()));

    ProcessBuilder psBuilder = new ProcessBuilder(processArgs).//
            redirectErrorStream(true);//

    final Process process = psBuilder.start();

    final Thread t = new Thread(() -> {
        try {// ww w .  j a va2s  .  c o m
            IOUtils.copy(process.getInputStream(), os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    t.start();

    process.waitFor();

    t.join();

    int resultCode = process.exitValue();
}