List of usage examples for java.lang Process destroyForcibly
public Process destroyForcibly()
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 {/* ww w . j a va 2s .c o m*/ return process.waitFor(); } finally { process.destroy(); if (process.isAlive()) process.destroyForcibly(); } }
From source file:org.cryptomator.frontend.webdav.mount.MacOsXAppleScriptWebDavMounter.java
private static void waitForProcessAndCheckSuccess(Process proc, long timeout, TimeUnit unit) throws CommandFailedException, IOException { try {// w w w . j a va 2 s . c o m boolean finishedInTime = proc.waitFor(timeout, unit); if (!finishedInTime) { proc.destroyForcibly(); throw new CommandFailedException("Command timed out."); } int exitCode = proc.exitValue(); if (exitCode != 0) { String error = IOUtils.toString(proc.getErrorStream(), StandardCharsets.UTF_8); throw new CommandFailedException( "Command failed with exit code " + exitCode + ". Stderr: " + error); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
From source file:org.wso2.security.tools.scanner.dependency.js.preprocessor.ReactFileDownloader.java
/** * Install npm modules which are referenced in package.json files. * * @param path Directory where the package.json file is placed. * @throws DownloaderException exception occurred while downloading NPM Modules. *//*from w w w . ja va2s. co m*/ private static void installNPMModules(String path) throws DownloaderException { Process process = null; try { ProcessBuilder processBuilder = new ProcessBuilder(JSScannerConstants.NPM, JSScannerConstants.INSTALL); processBuilder.directory(new File(path)); process = processBuilder.start(); process.waitFor(); } catch (IOException | InterruptedException e) { throw new DownloaderException("Error occurred while downloading NPM modules due to : ", e); } finally { if (process != null) { process.destroyForcibly(); } } }
From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java
public void validate(IRequest request, X509CertInfo info) throws ERejectException { CMS.debug("About to execute command: " + this.executable); ProcessBuilder pb = new ProcessBuilder(this.executable); // set up process environment Map<String, String> env = pb.environment(); for (String k : envVars.keySet()) { String v = request.getExtDataInString(envVars.get(k)); if (v != null) env.put(k, v);/* w w w . java 2 s.c o m*/ } for (String k : extraEnvVars.keySet()) { String v = request.getExtDataInString(extraEnvVars.get(k)); if (v != null) env.put(k, v); } Process p; String stdout = ""; String stderr = ""; boolean timedOut; try { p = pb.start(); timedOut = !p.waitFor(timeout, TimeUnit.SECONDS); if (timedOut) p.destroyForcibly(); else stdout = IOUtils.toString(p.getInputStream()); stderr = IOUtils.toString(p.getErrorStream()); } catch (Throwable e) { String msg = "Caught exception while executing command: " + this.executable; CMS.debug(msg); CMS.debug(e); throw new ERejectException(msg, e); } if (timedOut) throw new ERejectException("Request validation timed out"); int exitValue = p.exitValue(); CMS.debug("ExternalProcessConstraint: exit value: " + exitValue); CMS.debug("ExternalProcessConstraint: stdout: " + stdout); CMS.debug("ExternalProcessConstraint: stderr: " + stderr); if (exitValue != 0) throw new ERejectException(stdout); }
From source file:org.eclipse.swt.snippets.SnippetExplorer.java
/** * Test if the given command can be executed. * * @param command command to test/* w w w. j a v a2 s .co m*/ * @return <code>false</code> if executing the command failed for any reason */ private static boolean canRunCommand(String command) { try { final Process p = Runtime.getRuntime().exec(command); p.waitFor(150, TimeUnit.MILLISECONDS); if (p.isAlive()) { p.destroy(); p.waitFor(100, TimeUnit.MILLISECONDS); if (p.isAlive()) { p.destroyForcibly(); } } return true; } catch (Exception ex) { return false; } }
From source file:org.wso2.msf4j.ballerina.BallerinaService.java
@POST @Consumes(MediaType.APPLICATION_JSON)/*from ww w . j ava 2 s . c om*/ @Produces(MediaType.TEXT_PLAIN) @Path("/executeAsProcess") public Response executeBallerinaWithArgsAsProcess(BallerinaContent ballerinaContent) { UUID requestId = UUID.randomUUID(); log.info(requestId.toString() + " <<< " + new Gson().toJson(ballerinaContent)); String result; try { java.nio.file.Path path = Paths.get(Application.ballerinaTmp.toString(), requestId.toString() + ".bal"); Files.write(path, ballerinaContent.getContent().getBytes()); fileCleaningTracker.track(path.toFile(), ballerinaContent); List<String> processArgs = new ArrayList<>(); processArgs.add(Application.ballerinaPath.toString()); processArgs.add("run"); processArgs.add(path.toString()); processArgs.addAll(Arrays.asList(ballerinaContent.getArguments().split(";"))); ProcessBuilder processBuilder = new ProcessBuilder(processArgs); processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home")); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); if (!process.waitFor(8, TimeUnit.SECONDS)) { // Run the psfinder script which will get the pid of started ballerina process and kill that. Process exec = Runtime.getRuntime().exec( new String[] { Application.psFinder.toFile().getAbsolutePath(), requestId.toString() }); exec.waitFor(); process.destroyForcibly(); result = "Process took too long\nSystem will exit"; } else { result = IOUtils.toString(process.getInputStream()); } } catch (Exception e) { result = "Something went wrong. Try again"; log.error(e); } log.info(requestId.toString() + " >>> " + result); return Response.ok().entity(result).header("Access-Control-Allow-Origin", "*").build(); }
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 w w. j a v a2 s.c o 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:com.heliosdecompiler.helios.controller.ProcessController.java
public Process launchProcess(ProcessBuilder launch) throws IOException { Process process = launch.start(); try {/*from w ww. j a v a 2 s.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:com.streamsets.pipeline.stage.executor.shell.ShellExecutor.java
private void executeScript(Record record) throws StageException { File script = null;/* w w w. java 2s . com*/ try { script = File.createTempFile("sdc-script-executor", ".sh"); ELVars variables = getContext().createELVars(); RecordEL.setRecordInContext(variables, record); // Serialize the script into a file on disk (in temporary location) FileUtils.writeStringToFile(script, config.script); ImmutableList.Builder<String> commandBuilder = new ImmutableList.Builder<>(); if (impersonationMode != ImpersonationMode.DISABLED) { commandBuilder.add(sudo); commandBuilder.add("-E"); commandBuilder.add("-u"); commandBuilder.add(user); } commandBuilder.add(shell); commandBuilder.add(script.getPath()); List<String> commandLine = commandBuilder.build(); // External process configuration ProcessBuilder processBuilder = new ProcessBuilder(commandLine); for (Map.Entry<String, String> entry : config.environmentVariables.entrySet()) { processBuilder.environment().put(eval.eval(variables, entry.getKey(), String.class), eval.eval(variables, entry.getValue(), String.class)); } // Start process and configure forwarders for stderr/stdin LOG.debug("Executing script: {}", StringUtils.join(commandLine, " ")); Process process = processBuilder.start(); new Thread(new ProcessStdIOForwarder(false, process.getInputStream())).start(); new Thread(new ProcessStdIOForwarder(true, process.getErrorStream())).start(); int pid = retrievePidIfFeasible(process); LOG.debug("Created process with PID {}", pid); // User configures the maximal time for the script execution boolean finished = process.waitFor(timeout, TimeUnit.MILLISECONDS); if (!finished) { process.destroyForcibly(); throw new OnRecordErrorException(record, Errors.SHELL_002); } if (process.exitValue() != 0) { throw new OnRecordErrorException(record, Errors.SHELL_003, process.exitValue()); } } catch (OnRecordErrorException e) { errorRecordHandler.onError(e); } catch (Exception e) { errorRecordHandler.onError(new OnRecordErrorException(record, Errors.SHELL_001, e.toString(), e)); } finally { if (script != null && script.exists()) { script.delete(); } } }
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(/* ww w. ja va 2 s . co 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); } }