List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:net.pms.PMS.java
/** * Executes a new Process and creates a fork that waits for its results. * TODO Extend explanation on where this is being used. * @param name Symbolic name for the process to be launched, only used in the trace log * @param error (boolean) Set to true if you want PMS to add error messages to the trace pane * @param workDir (File) optional working directory to run the process in * @param params (array of Strings) array containing the command to call and its arguments * @return Returns true if the command exited as expected * @throws Exception TODO: Check which exceptions to use *///from w ww.j a v a 2s. co m private boolean checkProcessExistence(String name, boolean error, File workDir, String... params) throws Exception { logger.debug("launching: " + params[0]); try { ProcessBuilder pb = new ProcessBuilder(params); if (workDir != null) { pb.directory(workDir); } final Process process = pb.start(); OutputTextConsumer stderrConsumer = new OutputTextConsumer(process.getErrorStream(), false); stderrConsumer.start(); OutputTextConsumer outConsumer = new OutputTextConsumer(process.getInputStream(), false); outConsumer.start(); Runnable r = new Runnable() { public void run() { ProcessUtil.waitFor(process); } }; Thread checkThread = new Thread(r, "PMS Checker"); checkThread.start(); checkThread.join(60000); checkThread.interrupt(); checkThread = null; // XXX no longer used if (params[0].equals("vlc") && stderrConsumer.getResults().get(0).startsWith("VLC")) { return true; } // XXX no longer used if (params[0].equals("ffmpeg") && stderrConsumer.getResults().get(0).startsWith("FF")) { return true; } int exit = process.exitValue(); if (exit != 0) { if (error) { logger.info("[" + exit + "] Cannot launch " + name + " / Check the presence of " + params[0] + " ..."); } return false; } return true; } catch (Exception e) { if (error) { logger.error("Cannot launch " + name + " / Check the presence of " + params[0] + " ...", e); } return false; } }
From source file:org.cloudifysource.usm.launcher.DefaultProcessLauncher.java
private Process launch(final List<String> commandLineParams, final File workingDir, final int retries, final boolean redirectErrorStream, final File outputFile, final File errorFile, final LifecycleEvents event) throws USMException { if (outputFile == null && errorFile != null || outputFile != null && errorFile == null) { throw new IllegalArgumentException("Both output and error files must be set, or none of them"); }/*from w w w . j av a 2 s . c o m*/ if (redirectErrorStream && (outputFile != null || errorFile != null)) { throw new IllegalArgumentException( "If redirectError option is chosen, neither output file or error file can be set"); } List<String> modifiedCommandLineParams = null; modifiedCommandLineParams = commandLineParams; if (isDebugEvent(event)) { // create environment for debugging the event and modify the command line. modifyCommandLine(modifiedCommandLineParams, workingDir, outputFile, errorFile, event); logger.info("DEBUG BREAKPOINT!"); DebugHookInvoker dhi = new DebugHookInvoker(); final ClassLoader loader = this.configutaion.getDslClassLoader(); logger.info("DSL Class Loader is: " + loader); modifiedCommandLineParams = dhi.setUpDebugHook(this.configutaion.getServiceContext(), modifiedCommandLineParams, loader, this.debugMode); } else { modifyCommandLine(modifiedCommandLineParams, workingDir, outputFile, errorFile, event); } // JDK7 on Windows Specific modifications // See CLOUDIFY-1787 for more details. File tempBatchFile = null; if (shouldModifyCommandLineForJDK7(outputFile)) { tempBatchFile = createTempFileForJDK7(workingDir); modifyCommandLineForJDK7ProcessBuilder(modifiedCommandLineParams, outputFile, workingDir, tempBatchFile); } final String modifiedCommandLine = org.springframework.util.StringUtils .collectionToDelimitedString(modifiedCommandLineParams, " "); this.commandLine = modifiedCommandLineParams; int attempt = 1; USMException ex = null; while (attempt <= retries + 1) { final ProcessBuilder pb = new ProcessBuilder(modifiedCommandLineParams); pb.directory(workingDir); pb.redirectErrorStream(redirectErrorStream); final Map<String, String> env = createEnvironment(); pb.environment().putAll(env); try { logger.fine("Parsed command line: " + commandLineParams.toString()); final String fileInitialMessage = "Starting service process in working directory:'" + workingDir + "' " + "at:'" + new Date() + "' with command:'" + modifiedCommandLineParams + "'" + System.getProperty("line.separator"); if (outputFile != null) { appendMessageToFile(fileInitialMessage, outputFile); } if (errorFile != null) { appendMessageToFile(fileInitialMessage, errorFile); } return pb.start(); } catch (final IOException e) { ex = new USMException("Failed to start process with command line: " + modifiedCommandLine, e); logger.log(Level.SEVERE, "Process start attempt number " + attempt + " failed", ex); } ++attempt; } throw ex; }
From source file:org.apache.hadoop.util.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;/* w ww. j av a 2 s . c o m*/ 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 = Time.now(); } }
From source file:io.smartspaces.util.process.BaseNativeApplicationRunner.java
/** * Attempt the run./*from w w w . ja v a 2 s . c o m*/ * * @param firstTime * {@code true} if this is the first attempt * * @return the process that was created * * @throws SmartSpacesException * was not able to start the process the first time */ private Process attemptRun(boolean firstTime) throws SmartSpacesException { try { ProcessBuilder builder = new ProcessBuilder(commandLine); Map<String, String> processEnvironment = builder.environment(); if (cleanEnvironment) { processEnvironment.clear(); } modifyEnvironment(processEnvironment, environment); // If don't know the executable folder, the executable will be run in the // process directory of the Java program. if (executableFolder != null) { builder.directory(executableFolder); log.info(String.format("Starting up native code in folder %s", executableFolder.getAbsolutePath())); } return builder.start(); } catch (Exception e) { // Placed here so we can get the exception when thrown. if (firstTime) { runnerState.set(NativeApplicationRunnerState.STARTUP_FAILED); handleApplicationStartupFailed(); throw SmartSpacesException.newFormattedException(e, "Can't start up native application " + executablePath); } return null; } }
From source file:edu.rice.dca.soaplabPBS.PBSJob.java
/************************************************************************** * Create and return a ProcessBuilder filled with the command-line * arguments and environment as defined in the metadata and user * input data for this job.// w ww . j a va2 s .com * * It throws an exception when it was not able to fill the * ProcessBuilder. **************************************************************************/ protected ProcessBuilder getProcessBuilder() throws SoaplabException { // command-line arguments ProcessBuilder pb = new ProcessBuilder(createArgs()); pb.command().add(0, getExecutableName()); // environment from several sources... Map<String, String> env = pb.environment(); // ...from the user (as defined by the service metadata) addProperties(env, createEnvs()); // ...from the service configuration addProperties(env, Config.getMatchingProperties(Config.PROP_ENVAR, getServiceName(), this)); // ...combine the current PATH and Soaplab's addtopath properties addToPath(env, Config.getStrings(Config.PROP_ADDTOPATH_DIR, null, getServiceName(), this)); // working directory pb.directory(getJobDir()); return pb; }
From source file:org.pshdl.model.simulation.codegenerator.GoCodeGenerator.java
public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) { try {/*from w w w .j ava 2 s . co m*/ IHDLInterpreterFactory<NativeRunner> _xblockexpression = null; { final CharSequence dartCode = this.generateMainCode(); final File dutFile = new File(tempDir, "TestUnit.go"); Files.createParentDirs(dutFile); Files.write(dartCode, dutFile, StandardCharsets.UTF_8); final File testRunner = new File(tempDir, "runner.go"); final InputStream runnerStream = CCodeGenerator.class .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.go"); final FileOutputStream fos = new FileOutputStream(testRunner); try { ByteStreams.copy(runnerStream, fos); } finally { fos.close(); } String _absolutePath = testRunner.getAbsolutePath(); String _absolutePath_1 = dutFile.getAbsolutePath(); ProcessBuilder _processBuilder = new ProcessBuilder("/usr/local/go/bin/go", "build", _absolutePath, _absolutePath_1); ProcessBuilder _directory = _processBuilder.directory(tempDir); ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true); final ProcessBuilder goBuilder = _redirectErrorStream.inheritIO(); final Process goCompiler = goBuilder.start(); int _waitFor = goCompiler.waitFor(); boolean _notEquals = (_waitFor != 0); if (_notEquals) { throw new RuntimeException("Compilation of Go Program failed"); } _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() { public NativeRunner newInstance() { try { final File runnerExecutable = new File(tempDir, "runner"); String _absolutePath = runnerExecutable.getAbsolutePath(); ProcessBuilder _processBuilder = new ProcessBuilder(_absolutePath); ProcessBuilder _directory = _processBuilder.directory(tempDir); final ProcessBuilder goBuilder = _directory.redirectErrorStream(true); final Process goRunner = goBuilder.start(); InputStream _inputStream = goRunner.getInputStream(); OutputStream _outputStream = goRunner.getOutputStream(); String _absolutePath_1 = runnerExecutable.getAbsolutePath(); return new NativeRunner(_inputStream, _outputStream, GoCodeGenerator.this.em, goRunner, 5, _absolutePath_1); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:com.android.ide.common.process.MtlProcessExecutor.java
public ListenableFuture<ProcessResult> submit(@NonNull ProcessInfo processInfo, @NonNull final ProcessOutputHandler processOutputHandler) { final List<String> command = buildCommand(processInfo); mLogger.info("command: " + Joiner.on(' ').join(command)); final SettableFuture<ProcessResult> result = SettableFuture.create(); try {//from ww w . java 2s. co m // Launch the command line process. ProcessBuilder processBuilder = new ProcessBuilder(buildCommand(processInfo)); Map<String, Object> envVariableMap = processInfo.getEnvironment(); if (!envVariableMap.isEmpty()) { Map<String, String> env = processBuilder.environment(); for (Map.Entry<String, Object> entry : envVariableMap.entrySet()) { env.put(entry.getKey(), entry.getValue().toString()); } } else { Map<String, String> env = processBuilder.environment(); env.putAll(System.getenv()); } if (processInfo instanceof MtlProcessInfo) { MtlProcessInfo mtlProcessInfo = (MtlProcessInfo) processInfo; if (StringUtils.isNotEmpty(mtlProcessInfo.getWorkspace())) { processBuilder.directory(new File(mtlProcessInfo.getWorkspace())); } } // Start the process. Process process = processBuilder.start(); // Grab the output, and the exit code. final ProcessOutput output = processOutputHandler.createOutput(); ListenableFuture<Integer> outputFuture = grabProcessOutput(process, output); Futures.addCallback(outputFuture, new FutureCallback<Integer>() { @Override public void onSuccess(Integer exit) { try { output.close(); processOutputHandler.handleOutput(output); result.set(new ProcessResultImpl(command, exit)); } catch (Exception e) { result.set(new ProcessResultImpl(command, e)); } } @Override public void onFailure(@Nullable Throwable t) { result.set(new ProcessResultImpl(command, t)); } }); } catch (Exception e) { result.set(new ProcessResultImpl(command, e)); } return result; }
From source file:com.buaa.cfs.utils.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;/* ww w .j a v a 2 s. 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); } 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(), Charset.defaultCharset())); BufferedReader inReader = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); 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) { } catch (OutOfMemoryError oe) { LOG.error("Caught " + oe + ". One possible reason is that ulimit" + " setting of 'max user processes' is too low. If so, do" + " 'ulimit -u <largerNum>' and try again."); throw oe; } 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(); // make sure that the error thread exits joinThread(errThread); 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); } if (!completed.get()) { errThread.interrupt(); joinThread(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 = Time.monotonicNow(); } }
From source file:middleware.NewServerSocket.java
private void startDstat() { if (!sharedData.isRemoteServer()) { String[] cmd = { "/bin/bash", "./monitor.sh" }; ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(new File("rs-sysmon2")); try {/*w w w . j a v a 2 s . c om*/ dstat = pb.start(); } catch (IOException e) { e.printStackTrace(); } } else { if (sharedData.remoteServerUser.length() != 0) { if (System.getProperty("user.name").contentEquals("root")) { String[] cmd = { "/bin/bash", "shell/sync_time.sh", sharedData.getServerIpAddr() }; try { ntpdate = Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } } if (!dstatDeployed) { configureSetenv(); String[] cmd = { "/bin/bash", "shell/deploy_dstat.sh", sharedData.remoteServerUser, sharedData.getServerIpAddr() }; Process deployDstat = null; try { deployDstat = Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } dstatDeployed = true; if (deployDstat != null) { Interrupter interrupter = new Interrupter(Thread.currentThread()); interrupter.start(); try { deployDstat.waitFor(); interrupter.setOuterThreadWaiting(false); } catch (InterruptedException e) { failDeployDstat = true; } } if (configSetenv) { clearSetenv(); } } if (!failDeployDstat) { String[] cmd = { "/bin/bash", "shell/monitor_remote_server.sh", sharedData.remoteServerUser, sharedData.getServerIpAddr() }; try { Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } } } } // if (dstat != null) { // BufferedReader b = new BufferedReader(new InputStreamReader( // dstat.getInputStream())); // String line = ""; // // System.out.println("--------------"); // try { // while ((line = b.readLine()) != null) { // System.out.println(line); // } // } catch (IOException e) { // e.printStackTrace(); // } // System.out.println("--------------"); // // try { // b.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } }