Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

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

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:de.unibremen.informatik.tdki.combo.rewriting.FakeFilterRewriter.java

private void compileCode() throws InterruptedException, IOException {
    Process p = Runtime.getRuntime().exec("cc -c " + sourceDir + "db2ffinterface.c -I" + db2IncludeDir
            + " -fpic -D_REENTRANT -m64 -o " + outputDir + "db2ffinterface.o");
    printOutput(p);//w  w w.j  a v  a 2 s  .  co m
    p.waitFor();
    p = Runtime.getRuntime().exec("cc -shared -lpthread -o " + outputDir + "libDB2FakeFilter" + libNo
            + ".dylib " + outputDir + "db2ffinterface.o");
    printOutput(p);
    p.waitFor();
}

From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandlerWindowsRegistrationCommand.java

private String getCurrentProtocolHandlerRegistryValue() {
    BufferedReader stdout = null;
    String line;//from  w ww . j av a  2s. com

    try {
        final ProcessBuilder pb = new ProcessBuilder("reg", //$NON-NLS-1$
                "query", //$NON-NLS-1$
                PROTOCOL_HANDLER_REGISTRY_PATH, "/ve"); //$NON-NLS-1$
        pb.redirectErrorStream(true);

        final Process cmd = pb.start();
        int rc = cmd.waitFor();

        if (rc == 0) {
            stdout = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
            while ((line = stdout.readLine()) != null) {
                int idx = 0;
                /* @formatter:off
                 * the output contains at most one line like 
                 * 
                 *    (Default)    REG_EXPAND_SZ    "%USERPROFILE%\.vsts\latestIDE.cmd" "%1"
                 * 
                 * @formatter:on
                 */
                if ((idx = line.indexOf(PROTOCOL_HANDLER_REG_VALUE_TYPE)) < 0) {
                    continue;
                }

                return line.substring(idx + PROTOCOL_HANDLER_REG_VALUE_TYPE.length()).trim();
            }
        }
    } catch (final InterruptedException e) {
        log.warn("Protocol handler registration has been cancelled."); //$NON-NLS-1$
    } catch (final Exception e) {
        log.error("Error accessing Windows registry:", e); //$NON-NLS-1$
    } finally {
        tryClose(stdout);
    }

    return null;
}

From source file:com.thoughtworks.go.agent.AgentProcessParentImplTest.java

private Process mockProcess(final InputStream outputStream, final InputStream errorStream,
        final OutputStream inputStream) throws InterruptedException {
    final Process subProcess = mock(Process.class);
    when(subProcess.waitFor()).thenReturn(42);
    when(subProcess.getInputStream()).thenReturn(outputStream);
    when(subProcess.getErrorStream()).thenReturn(errorStream);
    when(subProcess.getOutputStream()).thenReturn(inputStream);
    return subProcess;
}

From source file:ape.SuspendNodeCommand.java

public boolean runImpl(String[] args) throws IOException {
    String nodeType = null;// w  w w .j a  v a 2  s.co  m
    nodeType = args[0];

    if (Main.VERBOSE)
        System.out.println("Nodetype" + args[0]);

    Process p;

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Suspend is about to execute the following command:");
        String cmd = "echo \"kill -19 \\$(ps aux | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > kill-node.sh && chmod +x kill-node.sh && ./kill-node.sh";
        System.out.println(cmd);
        /**
         * The above code block checks to see if a valid node type is passed.
         * If it is, then it sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh;
        try {
            sh = pb.start();
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            sh.waitFor();
        } catch (InterruptedException e) {
            System.out.println("The suspend node command caught an Interrupt...");
            e.printStackTrace();
            return false;
        }
        InputStream shIn = sh.getInputStream();
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the suspend process.");
            e.printStackTrace();
            return false;
        }
        return true;
    } else {
        System.err.println("Invalid node type.");
        return false;
    }
}

From source file:mitm.common.util.ProcessUtils.java

/**
 * Helper method that executes the given cmd and returns the output. The process will be destroyed 
 * if the process takes longer to execute than the timeout.  
 *//*  w  ww . java 2  s.c om*/
public static void executeCommand(List<String> cmd, long timeout, InputStream input, OutputStream output)
        throws IOException {
    Check.notNull(cmd, "cmd");

    if (cmd.size() == 0) {
        throw new IOException("Process is missing.");
    }

    /*
     * Used for reporting
     */
    String name = StringUtils.join(cmd, ",");

    /*
     * Watchdog that will be used to destroy the process on a timeout
     */
    TaskScheduler watchdog = new TaskScheduler(ProcessUtils.class.getCanonicalName() + "#" + name);

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        /*
         * Task that will destroy the process on a timeout
         */
        Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName());

        watchdog.addTask(processWatchdogTask, timeout);

        /*
         * Task that will interrup the current thread on a timeout
         */
        Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(),
                watchdog.getName());

        watchdog.addTask(threadInterruptTimeoutTask, timeout);

        /*
         * Send the input to the standard input of the process
         */
        if (input != null) {
            IOUtils.copy(input, process.getOutputStream());

            IOUtils.closeQuietly(process.getOutputStream());
        }

        /*
         * Get the standard output from the process
         */
        if (output != null) {
            IOUtils.copy(process.getInputStream(), output);
        }

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new IOException("Error executing [" + name + "]", e);
        }

        if (exitValue != 0) {
            throw new ProcessException("Error executing [" + name + "]. exit value: " + exitValue, exitValue);
        }
    } finally {
        /*
         * Need to cancel any pending tasks
         */
        watchdog.cancel();
    }
}

From source file:com.liferay.blade.cli.ConvertThemeCommand.java

public void importTheme(String themePath) throws Exception {
    Process process = Util.startProcess(_blade, "yo liferay-theme:import -p \"" + themePath + "\" -c "
            + compassSupport(themePath) + " --skip-install", _themesDir, false);

    int errCode = process.waitFor();

    if (errCode == 0) {
        _blade.out().println("Theme " + themePath + " migrated successfully");

        File theme = new File(themePath);

        FileUtils.deleteDirectory(theme);
    } else {//from  w w w .j  ava  2s  .  c  o m
        _blade.error("blade exited with code: " + errCode);
    }
}

From source file:hu.tvdr.serialport.serialport.java

public void SerialPortCall(File device, int baudrate, int flags) throws SecurityException, IOException {

    /* Check access permission */
    if (!device.canRead() || !device.canWrite()) {
        try {/*from  w ww .ja va 2s  .  c o m*/
            /* Missing read/write permission, trying to chmod the file */
            Process su;
            su = Runtime.getRuntime().exec("/system/bin/su");
            String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
            su.getOutputStream().write(cmd.getBytes());
            if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                throw new SecurityException();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException();
        }
    }

    mFd = open(device.getAbsolutePath(), baudrate, flags);
    if (mFd == null) {
        Log.e(TAG, "native open returns null");
        throw new IOException();
    }
    mFileInputStream = new FileInputStream(mFd);
    mFileOutputStream = new FileOutputStream(mFd);
}