Example usage for java.lang Process isAlive

List of usage examples for java.lang Process isAlive

Introduction

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

Prototype

public boolean isAlive() 

Source Link

Document

Tests whether the process represented by this Process is alive.

Usage

From source file:lohbihler.process.Test.java

public static void main(final String[] args) throws Exception {
    final ExecutorService executorService = Executors.newCachedThreadPool();

    final Process process = new ProcessBuilder("cmd").start();
    final InputReader input = new InputReader(process.getInputStream());
    final InputReader error = new InputReader(process.getErrorStream());

    executorService.execute(input);//  w ww.  j  av a2 s .com
    executorService.execute(error);
    final OutputStreamWriter out = new OutputStreamWriter(process.getOutputStream());

    Thread.sleep(1000);
    System.out.println("Input: " + input.getInput());
    System.out.println("Error: " + error.getInput());
    System.out.println("Alive: " + process.isAlive());
    System.out.println();

    out.append("PING 1.1.1.1 -n 1 -w 5000\r\n");
    out.flush();

    for (int i = 0; i < 7; i++) {
        Thread.sleep(1000);
        System.out.println("Input: " + input.getInput());
        System.out.println("Error: " + error.getInput());
        System.out.println("Alive: " + process.isAlive());
        System.out.println();
    }

    out.append("PING 1.1.1.1 -n 1 -w 2000\r\n");
    out.flush();

    for (int i = 0; i < 4; i++) {
        Thread.sleep(1000);
        System.out.println("Input: " + input.getInput());
        System.out.println("Error: " + error.getInput());
        System.out.println("Alive: " + process.isAlive());
        System.out.println();
    }

    process.destroy();

    executorService.shutdown();
}

From source file:com.qwazr.utils.process.ProcessUtils.java

public static Integer run(String commandLine) throws InterruptedException, IOException {
    Process process = Runtime.getRuntime().exec(commandLine);
    try {/*from   ww w.j  a v a2  s .c o m*/
        return process.waitFor();
    } finally {
        process.destroy();
        if (process.isAlive())
            process.destroyForcibly();
    }
}

From source file:org.apache.geode.internal.process.ProcessUtils.java

/**
 * Returns true if a process identified by the specified Process is currently running on this host
 * machine.//from   ww  w  .  jav a  2s  .c  om
 * 
 * @param process the Process to check
 * @return true if the Process is a currently running process
 */
public static boolean isProcessAlive(final Process process) {
    notNull(process, "Invalid process '" + process + "' specified");

    return process.isAlive();
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Starts the given process by calling process_builder.start();
 * Records the started processes pid and start date.
 *  //w ww .  jav a 2s  . c om
 * @param process_builder
 * @throws IOException 
 * @return returns any error in _1(), the pid in _2()
 */
public static Tuple2<String, String> launchProcess(final ProcessBuilder process_builder,
        final String application_name, final DataBucketBean bucket, final String aleph_root_path,
        final Optional<Tuple2<Long, Integer>> timeout_kill) {
    try {
        if (timeout_kill.isPresent()) {
            final Stream<String> timeout_stream = Stream.of("timeout", "-s", timeout_kill.get()._2.toString(),
                    timeout_kill.get()._1.toString());
            process_builder.command(Stream.concat(timeout_stream, process_builder.command().stream())
                    .collect(Collectors.toList()));
        }

        //starts the process, get pid back
        logger.debug("Starting process: " + process_builder.command().toString());
        final Process px = process_builder.start();
        String err = null;
        String pid = null;
        if (!px.isAlive()) {
            err = "Unknown error: " + px.exitValue() + ": "
                    + process_builder.command().stream().collect(Collectors.joining(" "));
            // (since not capturing output)
        } else {
            pid = getPid(px);
            //get the date on the pid file from /proc/<pid>
            final long date = getDateOfPid(pid);
            //record pid=date to aleph_root_path/pid_manager/bucket._id/application_name
            storePid(application_name, bucket, aleph_root_path, pid, date);
        }
        return Tuples._2T(err, pid);

    } catch (Throwable t) {
        return Tuples._2T(ErrorUtils.getLongForm("{0}", t), null);
    }
}

From source file:deincraftlauncher.start.StartMinecraft.java

private static void checkAlive(Process launch, Modpack pack) {

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override/*from  www.j  a  v  a 2  s  .  c o  m*/
        public void run() {
            if (!launch.isAlive()) {
                Platform.runLater(() -> {
                    System.out.println("minecraft stopped, process is dead!");
                    pack.setPackstarted(false);
                    pack.setStartState(PackViewHandler.StartState.Normal);
                    pack.setStartText("Spielen");
                });
            } else {
                checkAlive(launch, pack);
            }
        }
    }, 3000);
}

From source file:tv.bioscope.taskqueue.TaskQueueWorker.java

private static void createAlternateStreamAndWriteUrlToDatastore(final EventStream eventStream) {
    if (availableFeedIds.isEmpty()) {
        System.out.println("No available feeds to show stream!");
        return;//from  w  ww  . j a v a  2 s.c  om
    }
    if (streamIdToFeedInfoMap.containsKey(eventStream.streamId)) {
        System.out.println("Already created alternate stream. Ignoring..");
        return;
    }
    try {
        System.out.println("Executing create alternate stream task..");
        int feedId = availableFeedIds.iterator().next();
        availableFeedIds.remove(feedId);

        String[] ffmpeg = new String[] { "ffmpeg", "-re", "-i", decodeURL(eventStream.encodedUrl),
                "http://127.0.0.1:" + FFSERVER_PORT + "/" + "feed" + feedId + ".ffm" };

        // TODO : Create background process
        Process p = Runtime.getRuntime().exec(ffmpeg);
        if (p.isAlive()) {
            System.out.println("ffmpeg process alive. ");
        } else {
            System.out.println(
                    "ffmpeg process died. exitValue = " + p.exitValue() + "args = " + Arrays.toString(ffmpeg));
        }

        FeedInfo feedInfo = new FeedInfo();
        feedInfo.feedId = feedId;
        feedInfo.streamingProcess = p;
        streamIdToFeedInfoMap.put(eventStream.streamId, feedInfo);

        String alternateStreamUrl = "http://" + INSTANCE_IP + ":" + FFSERVER_PORT + "/" + "test" + feedId
                + ".mpg";

        Key streamKey = KeyFactory.createKey("EventStream", eventStream.streamId);
        try {
            Entity stream = dataStore.get(streamKey);
            stream.setProperty("encodedAlternateUrl", encodeURL(alternateStreamUrl));
            stream.setProperty("lastAlternateUrlUpdatedTimeMs", System.currentTimeMillis());
            dataStore.put(stream);
            System.out.println("Successfully updated alternate URL for stream");
        } catch (EntityNotFoundException e) {
            // ignore (to be handled as part of input validation)
        }

    } catch (Exception e) {
        System.out.println("Failed to create stream! Cause = " + e.getClass());
        e.printStackTrace();
    }
}

From source file:com.thinkbiganalytics.spark.shell.SparkClientUtil.java

/**
 * Gets the Spark version string by executing {@code spark-submit}.
 *
 * @throws IOException if the version string cannot be obtained
 *//*from  w  ww  .  j a  va 2  s.  c o  m*/
private static String getVersion() throws IOException {
    // Build spark-submit process
    final String sparkSubmitCommand = new StringJoiner(File.separator).add(getSparkHome()).add("bin")
            .add("spark-submit").toString();
    final Process process = new ProcessBuilder().command(sparkSubmitCommand, "--version")
            .redirectErrorStream(true).start();

    // Wait for process to complete
    boolean exited;
    try {
        exited = process.waitFor(10, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
        Thread.currentThread().interrupt();
        exited = !process.isAlive();
    }

    if (!exited) {
        throw new IOException("Timeout waiting for Spark version");
    }

    // Read stdout
    final byte[] bytes = new byte[1024];
    final int length = process.getInputStream().read(bytes);

    final String output = new String(bytes, 0, length, "UTF-8");
    final Matcher matcher = Pattern.compile("version ([\\d+.]+)").matcher(output);
    if (matcher.find()) {
        return matcher.group(1);
    } else {
        throw new IllegalStateException("Unable to determine version from Spark Submit");
    }
}

From source file:docs.AbstractGemFireIntegrationTests.java

protected static int waitForProcessToStop(Process process, File directory, long duration) {
    final long timeout = (System.currentTimeMillis() + duration);

    try {/*w ww.j ava  2 s  .  c  om*/
        while (process.isAlive() && System.currentTimeMillis() < timeout) {
            if (process.waitFor(DEFAULT_WAIT_INTERVAL, TimeUnit.MILLISECONDS)) {
                return process.exitValue();
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    return (process.isAlive() ? -1 : process.exitValue());
}

From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java

public static CommandOutput runProcess(ProcessBuilder builder) throws InterruptedException, IOException {
    builder.environment().putAll(System.getenv());
    StringBuilder output = new StringBuilder();
    boolean isStopped = false;
    final Process process = builder.start();
    try (BufferedReader outReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        while (!isStopped) {
            while (outReader.ready()) {
                String line = outReader.readLine();
                if (line != null && !line.isEmpty()) {
                    output.append(line);
                }//w w w .  j av  a 2 s .  c  o m
            }
            if (!process.isAlive()) {
                isStopped = true;
            } else {
                Thread.yield();
            }
        }
        outReader.close();
    }
    int exitCode = process.exitValue();
    //String output = convertStreamToString(process.getInputStream());
    String errorOutput = convertStreamToString(process.getErrorStream());
    return new CommandOutput(exitCode, output.toString(), errorOutput);
}

From source file:docs.AbstractGemFireIntegrationTests.java

@SuppressWarnings("all")
protected static boolean waitForProcessToStart(Process process, File directory, long duration) {
    final File processControl = new File(directory, DEFAULT_PROCESS_CONTROL_FILENAME);

    waitOnCondition(new Condition() {
        public boolean evaluate() {
            return processControl.isFile();
        }//from  w  ww .ja  v  a2  s .com
    }, duration);

    return process.isAlive();
}