List of usage examples for java.lang Process isAlive
public boolean isAlive()
From source file:com.heliosdecompiler.helios.controller.ProcessController.java
public Process launchProcess(ProcessBuilder launch) throws IOException { Process process = launch.start(); try {/*from www . ja v a 2s. c o m*/ lock.lock(); processes.add(process); } finally { lock.unlock(); } backgroundTaskHelper.submit(new BackgroundTask( Message.TASK_LAUNCH_PROCESS.format(launch.command().stream().collect(Collectors.joining(" "))), true, () -> { try { process.waitFor(); if (!process.isAlive()) { processes.remove(process); } } catch (InterruptedException ignored) { } }, () -> { process.destroyForcibly(); try { lock.lock(); processes.remove(process); } finally { lock.unlock(); } })); return process; }
From source file:org.structr.web.test.FrontendTest.java
protected int run(final String testName) { try (final Tx tx = app.tx()) { createAdminUser();//ww w . j a v a2s .c om createResourceAccess("_login", UiAuthenticator.NON_AUTH_USER_POST); tx.success(); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } try (final Tx tx = app.tx()) { String[] args = { "/bin/sh", "-c", "cd src/test/javascript ; PATH=./bin/`uname`/:$PATH casperjs/bin/casperjs --httpPort=" + httpPort + " test " + testName + ".js" }; Process proc = Runtime.getRuntime().exec(args); logger.log(Level.INFO, IOUtils.toString(proc.getInputStream())); String warnings = IOUtils.toString(proc.getErrorStream()); if (StringUtils.isNotBlank(warnings)) { logger.log(Level.WARNING, warnings); } final int maxRetries = 60; Integer exitValue = 1; // default is error try { int r = 0; while (proc.isAlive() && r < maxRetries) { Thread.sleep(1000); r++; } exitValue = proc.exitValue(); makeVideo(testName); return exitValue; } catch (IllegalThreadStateException ex) { logger.log(Level.WARNING, "Subprocess has not properly exited", ex); ex.printStackTrace(); } logger.log(Level.INFO, "casperjs subprocess returned with {0}", exitValue); tx.success(); } catch (Exception ex) { logger.log(Level.SEVERE, null, ex); } return 1; }
From source file:org.structr.web.basic.FrontendTest.java
protected int run(final String testName) { try (final Tx tx = app.tx()) { createAdminUser();//w w w .j av a 2 s. c o m createResourceAccess("_login", UiAuthenticator.NON_AUTH_USER_POST); tx.success(); } catch (Exception ex) { logger.error("", ex); } try (final Tx tx = app.tx()) { String[] args = { "/bin/sh", "-c", "cd src/test/javascript ; PATH=./bin/`uname`/:$PATH casperjs/bin/casperjs --httpPort=" + httpPort + " test " + testName + ".js" }; Process proc = Runtime.getRuntime().exec(args); logger.info(IOUtils.toString(proc.getInputStream())); String warnings = IOUtils.toString(proc.getErrorStream()); if (StringUtils.isNotBlank(warnings)) { logger.warn(warnings); } final int maxRetries = 60; Integer exitValue = 1; // default is error try { int r = 0; while (proc.isAlive() && r < maxRetries) { Thread.sleep(1000); r++; } exitValue = proc.exitValue(); makeVideo(testName); return exitValue; } catch (IllegalThreadStateException ex) { logger.warn("Subprocess has not properly exited", ex); logger.warn("", ex); } logger.info("casperjs subprocess returned with {}", exitValue); tx.success(); } catch (Exception ex) { logger.error("", ex); } return 1; }
From source file:tpt.dbweb.cat.evaluation.ReferenceEvaluator.java
/** * Call external command//w w w. j a va2 s . c o m * @param cmd * @return its std output as a string */ private String execExternalCommand(String cmd) { log.debug("executing command: {}", cmd); Process p = null; try { p = Runtime.getRuntime().exec(cmd); } catch (IOException e1) { e1.printStackTrace(); } InputStream is = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringWriter sw = new StringWriter(); try { while (p.isAlive()) { try { char[] buffer = new char[1024 * 4]; int n = 0; while (-1 != (n = br.read(buffer))) { sw.write(buffer, 0, n); } if (p.isAlive()) { Thread.sleep(10); } } catch (IOException e) { e.printStackTrace(); } } } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } String str = sw.toString(); return str; }
From source file:cc.arduino.packages.Uploader.java
protected boolean executeUploadCommand(String command[]) throws Exception { // Skip empty commands if (command == null || command.length == 0) return true; notFoundError = false;//from w ww. j a v a 2 s. co m int result = -1; try { if (verbose) { for (String c : command) System.out.print(c + " "); System.out.println(); } Process process = ProcessUtils.exec(command); programmerPid = process; new MessageSiphon(process.getInputStream(), this, 100); new MessageSiphon(process.getErrorStream(), this, 100); // wait for the process to finish, but not forever // kill the flasher process after 5 minutes to avoid 100% cpu spinning if (!process.waitFor(5, TimeUnit.MINUTES)) { process.destroyForcibly(); } if (!process.isAlive()) { result = process.exitValue(); } else { result = 0; } } catch (Exception e) { e.printStackTrace(); } return result == 0; }
From source file:cn.edu.zjnu.acm.judge.core.Judger.java
private boolean compile(RunRecord runRecord) throws IOException { String source = runRecord.getSource(); if (StringUtils.isEmptyOrWhitespace(source)) { return false; }//from w w w .ja v a 2 s. c o m Path work = runRecord.getWorkDirectory(); final String main = "Main"; Files.createDirectories(work); Path sourceFile = work.resolve(main + "." + runRecord.getLanguage().getSourceExtension()); //??? Files.copy(new ByteArrayInputStream(source.getBytes(Platform.getCharset())), sourceFile, StandardCopyOption.REPLACE_EXISTING); String compileCommand = runRecord.getLanguage().getCompileCommand(); log.debug("Compile Command: {}", compileCommand); // if (StringUtils.isEmptyOrWhitespace(compileCommand)) { return true; } assert compileCommand != null; // // VC++? // G++? Path compileInfo = work.resolve("compileinfo.txt"); Process process = ProcessCreationHelper.execute(new ProcessBuilder(compileCommand.split("\\s+")) .directory(work.toFile()).redirectOutput(compileInfo.toFile()).redirectErrorStream(true)::start); process.getInputStream().close(); try { process.waitFor(45, TimeUnit.SECONDS); } catch (InterruptedException ex) { throw new InterruptedIOException(); } //? String errorInfo; if (process.isAlive()) { process.destroy(); try { process.waitFor(); } catch (InterruptedException ex) { throw new InterruptedIOException(); } errorInfo = "Compile timeout\nOutput:\n" + collectLines(compileInfo); } else { errorInfo = collectLines(compileInfo); } log.debug("errorInfo = {}", errorInfo); Path executable = work.resolve(main + "." + runRecord.getLanguage().getExecutableExtension()); //?? log.debug("executable = {}", executable); boolean compileOK = Files.exists(executable); // if (!compileOK) { submissionMapper.updateResult(runRecord.getSubmissionId(), ResultType.COMPILE_ERROR, 0, 0); submissionMapper.saveCompileInfo(runRecord.getSubmissionId(), errorInfo); updateSubmissionStatus(runRecord); } return compileOK; }
From source file:io.stallion.utils.ProcessHelper.java
public CommandResult run() { String cmdString = String.join(" ", args); System.out.printf("----- Execute command: %s ----\n", cmdString); ProcessBuilder pb = new ProcessBuilder(args); if (!empty(directory)) { pb.directory(new File(directory)); }/* w w w . ja va 2s . c o m*/ Map<String, String> env = pb.environment(); CommandResult commandResult = new CommandResult(); Process p = null; try { if (showDotsWhileWaiting == null) { showDotsWhileWaiting = !inheritIO; } if (inheritIO) { p = pb.inheritIO().start(); } else { p = pb.start(); } BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!empty(input)) { Log.info("Writing input to pipe {0}", input); IOUtils.write(input, p.getOutputStream(), UTF8); p.getOutputStream().flush(); } while (p.isAlive()) { p.waitFor(1000, TimeUnit.MILLISECONDS); if (showDotsWhileWaiting == true) { System.out.printf("."); } } commandResult.setErr(IOUtils.toString(err)); commandResult.setOut(IOUtils.toString(out)); commandResult.setCode(p.exitValue()); if (commandResult.succeeded()) { info("\n---- Command execution completed ----\n"); } else { Log.warn("Command failed with error code: " + commandResult.getCode()); } } catch (IOException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(999); commandResult.setEx(e); } catch (InterruptedException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(998); commandResult.setEx(e); } Log.fine( "\n\n----Start shell command result----:\nCommand: {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n", cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr()); return commandResult; }
From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanCommandCallable.java
@Override public ScanCommandOutput call() { String commandToExecute = "command_not_yet_configured"; try {/* ww w.ja v a2 s .c o m*/ final ScanPaths scanPaths = scanPathsUtility .determineSignatureScannerPaths(scanCommand.getInstallDirectory()); final List<String> cmd = scanCommand.createCommandForProcessBuilder(logger, scanPaths, scanCommand.getOutputDirectory().getAbsolutePath()); cmd.add(scanCommand.getTargetPath()); commandToExecute = createPrintableCommand(cmd); logger.info(String.format("Black Duck CLI command: %s", commandToExecute)); final File standardOutFile = scanPathsUtility.createStandardOutFile(scanCommand.getOutputDirectory()); try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) { final ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream); final ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.environment().putAll(intEnvironmentVariables.getVariables()); if (!scanCommand.isDryRun()) { if (!StringUtils.isEmpty(scanCommand.getApiToken())) { processBuilder.environment().put("BD_HUB_TOKEN", scanCommand.getApiToken()); } else { processBuilder.environment().put("BD_HUB_PASSWORD", scanCommand.getPassword()); } } processBuilder.environment().put("BD_HUB_NO_PROMPT", "true"); final Process blackDuckCliProcess = processBuilder.start(); // The cli logs go the error stream for some reason final StreamRedirectThread redirectThread = new StreamRedirectThread( blackDuckCliProcess.getErrorStream(), splitOutputStream); redirectThread.start(); int returnCode = -1; try { returnCode = blackDuckCliProcess.waitFor(); // the join method on the redirect thread will wait until the thread is dead // the thread will die when it reaches the end of stream and the run method is finished redirectThread.join(); } finally { if (blackDuckCliProcess.isAlive()) { blackDuckCliProcess.destroy(); } if (redirectThread.isAlive()) { redirectThread.interrupt(); } } splitOutputStream.flush(); logger.info(IOUtils.toString(blackDuckCliProcess.getInputStream(), StandardCharsets.UTF_8)); logger.info("Black Duck Signature Scanner return code: " + returnCode); logger.info( "You can view the logs at: '" + scanCommand.getOutputDirectory().getCanonicalPath() + "'"); if (returnCode != 0) { return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, returnCode); } } } catch (final Exception e) { final String errorMessage = String.format("There was a problem scanning target '%s': %s", scanCommand.getTargetPath(), e.getMessage()); return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, errorMessage, e); } if (!scanCommand.isDryRun() && cleanupOutput) { FileUtils.deleteQuietly(scanCommand.getOutputDirectory()); } else if (scanCommand.isDryRun() && cleanupOutput) { // delete everything except dry run files final File[] outputFiles = scanCommand.getOutputDirectory().listFiles(); for (final File outputFile : outputFiles) { if (!DRY_RUN_FILES_TO_KEEP.contains(outputFile.getName())) { FileUtils.deleteQuietly(outputFile); } } } return ScanCommandOutput.SUCCESS(scanCommand.getName(), logger, scanCommand, commandToExecute); }
From source file:io.fabric8.maven.plugin.DebugMojo.java
private void portForward(Controller controller, String podName) throws MojoExecutionException { File file = getKubeCtlExecutable(controller); String command = file.getName(); log.info(/*from w w w . ja v a2s . c o m*/ "Port forwarding to port " + remoteDebugPort + " on pod " + podName + " using command: " + command); String arguments = " port-forward " + podName + " " + localDebugPort + ":" + remoteDebugPort; String commands = command + arguments; log.info("Executing command: " + commands); final String message = "port forward"; final Process process; try { process = Runtime.getRuntime().exec(file.getAbsolutePath() + arguments); Runtime.getRuntime().addShutdownHook(new Thread("mvn fabric8:run-interactive shutdown hook") { @Override public void run() { if (process != null) { log.info("Terminating port forward process:"); try { process.destroy(); } catch (Exception e) { log.error("Failed to terminate process " + message); } try { if (process != null && process.isAlive()) { process.destroyForcibly(); } } catch (Exception e) { log.error("Failed to forcibly terminate process " + message); } } } }); log.info(""); log.info("Now you can start a Remote debug execution in your IDE by using localhost and the debug port " + localDebugPort); log.info(""); processCommandAsync(process, createExternalProcessLogger(command + "> "), commands, message); } catch (Exception e) { throw new MojoExecutionException("Failed to execute process " + commands + " for " + message + ": " + e, e); } }
From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java
private void endProcess() { if (processEnded.compareAndSet(false, true)) { lock.expired.set(true);/* w w w .java2 s .c om*/ final Process proc = process.get(); if (proc != null) { while (proc.isAlive()) { try { PidProcess pidProcess = Processes.newPidProcess(proc); try { if (!pidProcess.destroyGracefully().waitFor(10, TimeUnit.SECONDS)) { throw new RuntimeException(); } } catch (Throwable t1) { if (!pidProcess.destroyForcefully().waitFor(10, TimeUnit.SECONDS)) { throw new RuntimeException(); } } } catch (Throwable t2) { try { proc.destroyForcibly().waitFor(10, TimeUnit.SECONDS); } catch (Throwable t3) { } } } } FileUtils.deleteQuietly(tmpDir); synchronized (locks) { locks.remove(lock); } synchronized (waiting) { portGroupsActive.remove(configuredPortGroup.get()); waiting.notifyAll(); } } }