List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:org.apache.hadoop.NodeHealthCheckerService.java
/** * Method used to terminate the node health monitoring service. * /*from w w w.j a v a2s. c o m*/ */ @Override public void stop() { if (!shouldRun(conf)) { return; } nodeHealthScriptScheduler.cancel(); if (shexec != null) { Process p = shexec.getProcess(); if (p != null) { p.destroy(); } } }
From source file:edu.umd.cs.marmoset.utilities.JProcess.java
public static void destroyProcessGroup(Process process, Logger log) { int pid = 0;/*from www .j a v a2 s. c om*/ try { pid = getPid(process); log.debug("PID to be killed = " + pid); String command = "kill -9 -" + pid; String[] cmd = command.split("\\s+"); Process kill = Runtime.getRuntime().exec(cmd); log.warn("Trying to kill the process group leader: " + command); kill.waitFor(); } catch (IOException e) { // if we can't execute the kill command, then try to destroy the process log.warn("Unable to execute kill -9 -" + pid + "; now calling process.destroy()"); } catch (InterruptedException e) { log.error("kill -9 -" + pid + " process was interrupted! Now calling process.destroy()"); } catch (IllegalAccessException e) { log.error("Illegal field access to PID field; calling process.destroy()", e); } catch (NoSuchFieldException e) { log.error("Cannot find PID field; calling process.destroy()", e); } finally { // call process.destroy() whether or not "kill -9 -<pid>" worked // in order to maintain proper internal state process.destroy(); } }
From source file:org.apache.tika.batch.fs.FSBatchTestBase.java
protected void destroyProcess(Process p) { if (p == null) return;//from w w w.j a v a2s . c om try { p.exitValue(); } catch (IllegalThreadStateException e) { p.destroy(); } }
From source file:net.pickapack.io.cmd.CommandLineHelper.java
/** * * @param cmd//from www . j a v a 2 s .c om * @param waitFor * @return */ public static int invokeNativeCommand(String[] cmd, boolean waitFor) { try { Runtime r = Runtime.getRuntime(); final Process ps = r.exec(cmd); // ProcessBuilder pb = new ProcessBuilder(cmd); // Process ps = pb.start(); new Thread() { { setDaemon(true); } @Override public void run() { try { IOUtils.copy(ps.getInputStream(), System.out); } catch (IOException e) { e.printStackTrace(); } } }.start(); new Thread() { { setDaemon(true); } @Override public void run() { try { IOUtils.copy(ps.getErrorStream(), System.out); } catch (IOException e) { e.printStackTrace(); } } }.start(); if (waitFor) { int exitValue = ps.waitFor(); if (exitValue != 0) { System.out.println("WARN: Process exits with non-zero code: " + exitValue); } ps.destroy(); return exitValue; } return 0; } catch (Exception e) { e.printStackTrace(); return -1; } }
From source file:msec.org.Tools.java
static public int runCommand(String[] cmd, StringBuffer sb, boolean waitflag) { Process pid = null; ProcessBuilder build = new ProcessBuilder(cmd); build.redirectErrorStream(true);/* w w w .j a v a2 s. c om*/ try { pid = build.start(); } catch (Exception e) { e.printStackTrace(); return -1; } if (sb != null) { //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024); InputStream in = pid.getInputStream(); byte[] buf = new byte[10240]; try { while (true) { int len = in.read(buf); if (len <= 0) { break; } sb.append(new String(buf, 0, len)); } } catch (Exception e) { } } if (waitflag) { try { pid.waitFor(); int v = pid.exitValue(); pid.destroy(); return v; } catch (Exception e) { } } return 0; }
From source file:it.polimi.modaclouds.qos.linebenchmark.solver.SolutionEvaluator.java
private void runWithLQNS() { StopWatch timer = new StopWatch(); String solverProgram = "lqns"; String command = solverProgram + " " + filePath + " -f"; //using the fast option logger.info("Launch: " + command); //String command = solverProgram+" "+filePath; //without using the fast option try {//from ww w . j a v a 2 s . co m ProcessBuilder pb = new ProcessBuilder(splitToCommandArray(command)); //start counting timer.start(); Process proc = pb.start(); readStream(proc.getInputStream(), false); readStream(proc.getErrorStream(), true); int exitVal = proc.waitFor(); //stop counting timer.stop(); proc.destroy(); //evaluation error messages if (exitVal == LQNS_RETURN_SUCCESS) ; else if (exitVal == LQNS_RETURN_MODEL_FAILED_TO_CONVERGE) { System.err.println(Main.LQNS_SOLVER + " exited with " + exitVal + ": The model failed to converge. Results are most likely inaccurate. "); System.err.println("Analysis Result has been written to: " + resultfilePath); } else { String message = ""; if (exitVal == LQNS_RETURN_INVALID_INPUT) { message = solverProgram + " exited with " + exitVal + ": Invalid Input."; } else if (exitVal == LQNS_RETURN_FATAL_ERROR) { message = solverProgram + " exited with " + exitVal + ": Fatal error"; } else { message = solverProgram + " returned an unrecognised exit value " + exitVal + ". Key: 0 on success, 1 if the model failed to meet the convergence criteria, 2 if the input was invalid, 4 if a command line argument was incorrect, 8 for file read/write problems and -1 for fatal errors. If multiple input files are being processed, the exit code is the bit-wise OR of the above conditions."; } System.err.println(message); } } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //tell listeners that the evaluation has been performed EvaluationCompletedEvent evaluationCompleted = new EvaluationCompletedEvent(this, 0, null); evaluationCompleted.setEvaluationTime(timer.getTime()); evaluationCompleted.setSolverName(solver); evaluationCompleted.setModelPath(filePath.getFileName()); for (ActionListener l : listeners) l.actionPerformed(evaluationCompleted); }
From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java
public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception { boolean isNew = false; if (cfg.getProcess() != null || isNew) { LOG.info("Stopping Launchpad " + cfg.getId()); boolean destroy = true; final int twoMinutes = 2 * 60 * 1000; final File controlPortFile = getControlPortFile(cfg.getDirectory()); LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists()); if (controlPortFile.exists()) { // reading control port int controlPort = -1; String secretKey = null; LineNumberReader lnr = null; String serverName = null; try { lnr = new LineNumberReader(new FileReader(controlPortFile)); final String portLine = lnr.readLine(); final int pos = portLine.indexOf(':'); controlPort = Integer.parseInt(portLine.substring(pos + 1)); if (pos > 0) { serverName = portLine.substring(0, pos); }//from w w w . j a va 2s. c o m secretKey = lnr.readLine(); } catch (final NumberFormatException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } catch (final IOException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } finally { IOUtils.closeQuietly(lnr); } if (controlPort != -1) { final List<String> hosts = new ArrayList<String>(); if (serverName != null) { hosts.add(serverName); } hosts.add("localhost"); hosts.add("127.0.0.1"); LOG.debug("Found control port " + controlPort); int index = 0; while (destroy && index < hosts.size()) { final String hostName = hosts.get(index); Socket clientSocket = null; DataOutputStream out = null; BufferedReader in = null; try { LOG.debug("Trying to connect to " + hostName + ":" + controlPort); clientSocket = new Socket(); // set a socket timeout clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes); // without that, read() call on the InputStream associated with this Socket is infinite clientSocket.setSoTimeout(twoMinutes); LOG.debug(hostName + ":" + controlPort + " connection estabilished, sending the 'stop' command..."); out = new DataOutputStream(clientSocket.getOutputStream()); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); if (secretKey != null) { out.writeBytes(secretKey); out.write(' '); } out.writeBytes("stop\n"); in.readLine(); destroy = false; LOG.debug("'stop' command sent to " + hostName + ":" + controlPort); } catch (final Throwable ignore) { // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions // we ignore this for now LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort + " due to: " + ignore.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(clientSocket); } index++; } } } if (cfg.getProcess() != null) { final Process process = cfg.getProcess(); if (!destroy) { // as shutdown might block forever, we use a timeout final long now = System.currentTimeMillis(); final long end = now + twoMinutes; LOG.debug("Waiting for process to stop..."); while (isAlive(process) && (System.currentTimeMillis() < end)) { try { Thread.sleep(2500); } catch (InterruptedException e) { // ignore } } if (isAlive(process)) { LOG.debug("Process timeout out after 2 minutes"); destroy = true; } else { LOG.debug("Process stopped"); } } if (destroy) { LOG.debug("Destroying process..."); process.destroy(); LOG.debug("Process destroyed"); } cfg.setProcess(null); } } else { LOG.warn("Launchpad already stopped"); } }
From source file:com.diversityarrays.kdxplore.trialdesign.RscriptFinderPanel.java
private void doCheckScriptPath() { String scriptPath = scriptPathField.getText().trim(); BackgroundTask<Either<String, String>, Void> task = new BackgroundTask<Either<String, String>, Void>( "Checking...", true) { @Override//www . j av a 2s . co m public Either<String, String> generateResult(Closure<Void> arg0) throws Exception { ProcessBuilder findRScript = new ProcessBuilder(scriptPath, "--version"); Process p = findRScript.start(); while (!p.waitFor(1000, TimeUnit.MILLISECONDS)) { if (backgroundRunner.isCancelRequested()) { p.destroy(); throw new CancellationException(); } } if (0 == p.exitValue()) { String output = Algorithms.readContent(null, p.getInputStream()); versionNumber = Algorithms.readContent(null, p.getErrorStream()); return Either.right(output); } errorOutput = Algorithms.readContent("Error Output:", p.getErrorStream()); if (errorOutput.isEmpty()) { errorOutput = "No error output available"; return Either.left(errorOutput); } return Either.left(errorOutput); } @Override public void onException(Throwable t) { onScriptPathChecked.accept(Either.left(t)); } @Override public void onCancel(CancellationException ce) { onScriptPathChecked.accept(Either.left(ce)); } @Override public void onTaskComplete(Either<String, String> either) { if (either.isLeft()) { MsgBox.error(RscriptFinderPanel.this, either.left(), "Error Output"); } else { TrialDesignPreferences.getInstance().setRscriptPath(scriptPath); onScriptPathChecked.accept(Either.right(scriptPath)); checkOutput = either.right(); } } }; backgroundRunner.runBackgroundTask(task); }
From source file:com.palantir.tslint.Linter.java
public void lint(IResource resource, String configurationPath) throws IOException { String resourceName = resource.getName(); if (resource instanceof IFile && resourceName.endsWith(".ts") && !resourceName.endsWith(".d.ts")) { IFile file = (IFile) resource;// w ww . j a v a 2 s .c o m String linterPath = TSLintPlugin.getLinterPath(); String resourcePath = resource.getRawLocation().toOSString(); // remove any pre-existing markers for the given file deleteMarkers(file); // start tslint and get its output ProcessBuilder processBuilder = new ProcessBuilder(this.nodePath, linterPath, "-f", resourcePath, "-t", "json", "-c", configurationPath); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), Charsets.UTF_8)); String jsonString = reader.readLine(); // now that we have the complete output, terminate the process process.destroy(); if (jsonString != null) { ObjectMapper objectMapper = new ObjectMapper(); RuleFailure[] ruleFailures = objectMapper.readValue(jsonString, RuleFailure[].class); for (RuleFailure ruleFailure : ruleFailures) { addMarker(ruleFailure); } } } }
From source file:org.rhq.plugins.jmx.test.JMXPluginTest.java
@AfterClass public void stopTestServers() { for (Process process : this.testServerJvms) { process.destroy(); }/* www. ja v a 2 s .com*/ }