List of usage examples for java.lang ProcessBuilder environment
Map environment
To view the source code for java.lang ProcessBuilder environment.
Click Source Link
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }/* ww w . j av a 2s . c o m*/ this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }
From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java
/** * {@inheritDoc}//w w w . j a v a2 s .com */ @Override public void launchProcess(final File jobDirectory, final Map<String, String> environmentVariablesMap, final List<String> commandLine, final boolean interactive) throws JobLaunchException { if (!launched.compareAndSet(false, true)) { throw new IllegalStateException("Job already launched"); } final ProcessBuilder processBuilder = new ProcessBuilder(); // Validate job running directory if (jobDirectory == null) { throw new JobLaunchException("Job directory is null"); } else if (!jobDirectory.exists()) { throw new JobLaunchException("Job directory does not exist: " + jobDirectory); } else if (!jobDirectory.isDirectory()) { throw new JobLaunchException("Job directory is not a directory: " + jobDirectory); } else if (!jobDirectory.canWrite()) { throw new JobLaunchException("Job directory is not writable: " + jobDirectory); } final Map<String, String> currentEnvironmentVariables = processBuilder.environment(); if (environmentVariablesMap == null) { throw new JobLaunchException("Job environment variables map is null"); } // Merge job environment variables into process inherited environment environmentVariablesMap.forEach((key, value) -> { final String replacedValue = currentEnvironmentVariables.put(key, value); if (StringUtils.isBlank(replacedValue)) { log.debug("Added job environment variable: {}={}", key, value); } else if (!replacedValue.equals(value)) { log.debug("Set job environment variable: {}={} (previous value: {})", key, value, replacedValue); } }); // Validate arguments if (commandLine == null) { throw new JobLaunchException("Job command-line arguments is null"); } else if (commandLine.isEmpty()) { throw new JobLaunchException("Job command-line arguments are empty"); } // Configure arguments log.info("Job command-line: {}", Arrays.toString(commandLine.toArray())); final List<String> expandedCommandLine; try { expandedCommandLine = expandCommandLineVariables(commandLine, Collections.unmodifiableMap(currentEnvironmentVariables)); } catch (final EnvUtils.VariableSubstitutionException e) { throw new JobLaunchException("Job command-line arguments variables could not be expanded"); } if (!commandLine.equals(expandedCommandLine)) { log.info("Job command-line with variables expanded: {}", Arrays.toString(expandedCommandLine.toArray())); } processBuilder.command(expandedCommandLine); if (interactive) { processBuilder.inheritIO(); } else { processBuilder.redirectError(PathUtils.jobStdErrPath(jobDirectory).toFile()); processBuilder.redirectOutput(PathUtils.jobStdOutPath(jobDirectory).toFile()); } if (killed.get()) { log.info("Job aborted, skipping launch"); } else { log.info("Launching job"); try { processReference.set(processBuilder.start()); } catch (final IOException | SecurityException e) { throw new JobLaunchException("Failed to launch job: ", e); } log.info("Process launched (pid: {})", getPid(processReference.get())); } }
From source file:org.h3270.host.S3270.java
/** * Constructs a new S3270 object. The s3270 subprocess (which does the communication with the host) is immediately started and * connected to the target host. If this fails, the constructor will throw an appropriate exception. * /*from w ww . j a v a 2s . c o m*/ * @param hostname * the name of the host to connect to * @param configuration * the h3270 configuration, derived from h3270-config.xml * @throws org.h3270.host.UnknownHostException * if <code>hostname</code> cannot be resolved * @throws org.h3270.host.HostUnreachableException * if the host cannot be reached * @throws org.h3270.host.S3270Exception * for any other error not matched by the above */ public S3270(String logicalUnit, String hostname, Properties properties) { this.logicalUnit = logicalUnit; this.hostname = hostname; this.screen = new S3270Screen(); String commandLine = buildCommandLine(logicalUnit, hostname, properties); try { ProcessBuilder pb = new ProcessBuilder(commandLine.split(" ")); // If we are not on Windows, we can force s3270 to use UTF-8 // encoding for screen dumps, so we are independent from // the system locale. On Windows, that doesn't work, so // we have to rely on the system code page being set to a // reasonable value. if (!System.getProperty("os.name").startsWith("Windows")) { Map<String, String> env = pb.environment(); env.put("LANG", "en_US.UTF-8"); } logger.info("Starting s3270: " + commandLine); s3270 = pb.start(); String systemEncoding = System.getProperty("file.encoding"); String encoding = systemEncoding != null ? systemEncoding : "ISO-8859-1"; out = new PrintWriter(new OutputStreamWriter(s3270.getOutputStream(), encoding)); in = new BufferedReader(new InputStreamReader(s3270.getInputStream(), encoding)); errorReader = new ErrorReader(); errorReader.start(); waitFormat(); } catch (IOException ex) { throw new RuntimeException("IO Exception while starting s3270", ex); } }
From source file:org.pentaho.di.job.entries.shell.JobEntryShell.java
private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) { FileObject fileObject = null; String realScript = null;//from ww w. j ava 2 s . c o m FileObject tempFile = null; try { // What's the exact command? String[] base = null; List<String> cmds = new ArrayList<String>(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn", Const.getOS())); } if (insertScript) { realScript = environmentSubstitute(script); } else { String realFilename = environmentSubstitute(getFilename()); fileObject = KettleVFS.getFileObject(realFilename, this); } if (Const.getOS().equals("Windows 95")) { base = new String[] { "command.com", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else if (Const.getOS().startsWith("Windows")) { base = new String[] { "cmd.exe", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else { if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } base = new String[] { KettleVFS.getFilename(fileObject) }; } // Construct the arguments... if (argFromPrevious && cmdRows != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } cmdline.append('"'); cmds.add(cmdline.toString()); } else { // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } } } else if (args != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); for (int i = 0; i < args.length; i++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(args[i])); } cmdline.append('"'); cmds.add(cmdline.toString()); } else { for (int i = 0; i < args.length; i++) { cmds.add(args[i]); } } } StringBuffer command = new StringBuffer(); Iterator<String> it = cmds.iterator(); boolean first = true; while (it.hasNext()) { if (!first) { command.append(' '); } else { first = false; } command.append(it.next()); } if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand", command.toString())); } // Build the environment variable list... ProcessBuilder procBuilder = new ProcessBuilder(cmds); Map<String, String> env = procBuilder.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) { String vfsFilename = environmentSubstitute(getWorkDirectory()); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this))); procBuilder.directory(file); } Process proc = procBuilder.start(); // any error message? StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)", true); // any output? StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)"); // kick them off Thread errorLoggerThread = new Thread(errorLogger); errorLoggerThread.start(); Thread outputLoggerThread = new Thread(outputLogger); outputLoggerThread.start(); proc.waitFor(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished", command.toString())); } // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus", environmentSubstitute(getFilename()), "" + result.getExitStatus())); } result.setNrErrors(1); } // wait until loggers read all data from stdout and stderr errorLoggerThread.join(); outputLoggerThread.join(); // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (IOException ioe) { logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell", environmentSubstitute(getFilename()), ioe.toString()), ioe); result.setNrErrors(1); } catch (InterruptedException ie) { logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted", environmentSubstitute(getFilename()), ie.toString()), ie); result.setNrErrors(1); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError", environmentSubstitute(getFilename()), e.toString()), e); result.setNrErrors(1); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { BaseMessages.getString(PKG, "JobShell.UnexpectedError", tempFile.toString(), e.toString()); } } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } }
From source file:com.thoughtworks.cruise.util.command.CommandLine.java
private Process createProcess(EnvironmentVariableContext environmentVariableContext, ConsoleOutputStreamConsumer consumer) { final String msgCommandInfo = "Executing: " + toString(getCommandLineForDisplay(), true); ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine()); LOG.debug(msgCommandInfo);/*from w ww . jav a 2 s .c o m*/ if (workingDir != null) { LOG.debug("Using working directory " + workingDir.getAbsolutePath()); processBuilder.directory(workingDir); } setEnvironmentVariables(processBuilder, environmentVariableContext, consumer); processBuilder.environment().putAll(env); Process process; try { LOG.debug("START command " + msgCommandInfo); process = processBuilder.start(); LOG.debug("END command " + msgCommandInfo); } catch (IOException e) { throw new CommandLineException( "Error happens when " + msgCommandInfo + "\n Make sure this command can execute manually.", e); } return process; }
From source file:com.tencent.gaia.portal.util.Shell.java
/** * Run a command/*from www .j a va2s . c o m*/ */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask = null; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } builder.redirectErrorStream(redirectErrorStream); if (Shell.WINDOWS) { synchronized (WindowsProcessLaunchLock) { // To workaround the race condition issue with child processes // inheriting unintended handles during process launch that can // lead to hangs on reading output and error streams, we // serialize process creation. More info available at: // http://support.microsoft.com/kb/315939 process = builder.start(); } } else { process = builder.start(); } if (timeOutInterval > 0) { timeOutTimer = new Timer("Shell command timeout"); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ise) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if (timeOutTimer != null) { timeOutTimer.cancel(); } // close the input stream try { // JDK 7 tries to automatically drain the input streams for us // when the process exits, but since close is not synchronized, // it creates a race if we close the stream first and the same // fd is recycled. the stream draining thread will attempt to // drain that fd!! it may block, OOM, or cause bizarre behavior // see: https://bugs.openjdk.java.net/browse/JDK-8024521 // issue is fixed in build 7u60 InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } try { if (!completed.get()) { errThread.interrupt(); errThread.join(); } } catch (InterruptedException ie) { LOG.warn("Interrupted while joining errThread"); } try { InputStream stderr = process.getErrorStream(); synchronized (stderr) { errReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = System.currentTimeMillis(); } }
From source file:org.knime.knip.ilastik.nodes.headless.IlastikHeadlessNodeModel.java
/** * @param exec/*from w w w . j a va2 s .c o m*/ * @throws IOException * @throws InterruptedException * @throws CanceledExecutionException * @throws URISyntaxException */ private void runIlastik(final String tmpDirPath, final List<String> inFiles, final ExecutionContext exec) throws IOException, InterruptedException { // get path of ilastik final String path = IlastikPreferencePage.getPath(); String outpath; try { outpath = FileUtil.resolveToPath(FileUtil.toURL(m_pathToIlastikProjectFileModel.getStringValue())) .toAbsolutePath().toString(); } catch (InvalidPathException | URISyntaxException e) { throw new IllegalArgumentException("The Path to the project file could not be resolved: " + e, e); } if (outpath == null) { throw new IllegalArgumentException("The Path to the project file could not be resolved."); } // DO NOT TOUCH THIS ORDER! inFiles.add(0, path); inFiles.add(1, "--headless"); inFiles.add(2, "--project=".concat(outpath)); inFiles.add(3, "--output_format=multipage tiff"); inFiles.add(4, "--output_filename_format=".concat(tmpDirPath).concat("{nickname}" + RESULT_IMG_SUFFIX)); KNIPGateway.log().debug("Executing ilastik with " + String.join(", ", inFiles)); // build process with project and images ProcessBuilder pB = new ProcessBuilder(inFiles); // limit cpu + memory usage final Map<String, String> env = pB.environment(); env.put("LAZYFLOW_THREADS", String.valueOf(m_ilastikThreadCount.getIntValue())); env.put("LAZYFLOW_TOTAL_RAM_MB", String.valueOf(m_ilastikMaxMemory.getIntValue())); // run ilastik Process p = pB.start(); // write ilastik output to knime console redirectToKnimeConsole(p.getInputStream(), DirectedLogServiceFactory.debug()); redirectToKnimeConsole(p.getErrorStream(), DirectedLogServiceFactory.error()); try { while (!p.waitFor(500, TimeUnit.MILLISECONDS)) { exec.checkCanceled(); } } catch (CanceledExecutionException cee) { KNIPGateway.log().error("Execution canceled, closing Ilastik now."); p.destroy(); } // 0 indicates successful execution if (p.exitValue() != 0) { throw new IllegalStateException("Execution of ilastik was not successful."); } }
From source file:sorcer.launcher.JavaProcessBuilder.java
public Process2 startProcess() throws IOException { ProcessBuilder procBld = new ProcessBuilder().command(command); if (debugger) { procBld.command().addAll(// w w w .j a va 2 s.c o m Arrays.asList("-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,address=" + debugPort)); } procBld.command().addAll(_D(properties)); String classPath = StringUtils.join(classPathList, File.pathSeparator); procBld.command().addAll(asList("-classpath", classPath, mainClass)); if (parameters != null) { procBld.command().addAll(parameters); } if (workingDir == null) { // the default // make explicit for logging purpose workingDir = new File(System.getProperty("user.dir")); } procBld.directory(workingDir); Map<String, String> env = procBld.environment(); updateEnvironment(env); StringBuilder cmdStr = new StringBuilder("[").append(workingDir.getPath()).append("] ") .append(StringUtils.join(procBld.command(), " ")); if (output != null) { cmdStr.append(" > ").append(output.getPath()); } log.info(cmdStr.toString()); redirectIO(procBld); Process proc = null; try { proc = procBld.start(); try { // give it a moment to exit on error Thread.sleep(100); } catch (InterruptedException ignored) { //ignore } // if the next call throws exception, then we're probably good - // process hasn't finished yet. int x = proc.exitValue(); throw new IllegalStateException("Process exited with value " + x); } catch (IllegalThreadStateException x) { return new Process2(proc); } }
From source file:org.pepstock.jem.node.tasks.JobTask.java
/** * Internal method which creates the process, preparing environment * variables, creating directories, setting listener of output and error * log, and wait for end of job execution. * /*from w w w. ja v a 2 s .co m*/ * @return return code of execution * @throws NodeMessageException * @throws InterruptedException * @throws Exception occurs if there is any error */ private int launchProcess() throws IOException, NodeMessageException, InterruptedException { int returnCode = 0; Process process = null; try { String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser(); AbstractFactory currFactory = (AbstractFactory) getFactory(); boolean useSudo = currFactory.isUseSudo() && !user.equalsIgnoreCase(Main.getNode().getUser()); // create a process builder ProcessBuilder builder = new ProcessBuilder(); Shell shell = CurrentPlatform.getInstance().getShell(); String command = CurrentPlatform.getInstance().getCommand(job, getCommand(), useSudo); builder.command(shell.getName(), shell.getParameters(), command); // set directory where execute process if (getStartDir() != null) { builder.directory(new File(getStartDir())); } // load variable environment from a temporary maps that you can use // inside of configure method. Map<String, String> env = getEnv(); Map<String, String> map = builder.environment(); for (Map.Entry<String, String> e : env.entrySet()) { map.put(e.getKey(), e.getValue()); } // writes JEM log with headers JobLogManager.printHeader(job); // start process and save instance process = builder.start(); // wait for end of job execution returnCode = process.waitFor(); // check if cancelled, setting the return code 222 if (isCancelled) { returnCode = Result.CANCELED; } } finally { if (process != null) { process.destroy(); } } return returnCode; }
From source file:org.apache.bookkeeper.util.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;// w w w .j a v a2s .c om ShellTimeoutTimerTask timeoutTimerTask = null; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } if (Shell.WINDOWS) { synchronized (WindowsProcessLaunchLock) { // To workaround the race condition issue with child processes // inheriting unintended handles during process launch that can // lead to hangs on reading output and error streams, we // serialize process creation. More info available at: // http://support.microsoft.com/kb/315939 process = builder.start(); } } else { process = builder.start(); } if (timeOutInterval > 0) { timeOutTimer = new Timer("Shell command timeout"); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader( new InputStreamReader(process.getErrorStream(), Charsets.UTF_8)); BufferedReader inReader = new BufferedReader( new InputStreamReader(process.getInputStream(), Charsets.UTF_8)); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ise) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if (timeOutTimer != null) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); } try { errReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = MathUtils.now(); } }