/** * Starts a native process on the server * * @param command the command to start the process * @param dir the dir in which the process starts */ static String startProcess(String command, String dir) throws IOException { StringBuffer ret = new StringBuffer(); String[] comm = new String[3]; comm[0] = COMMAND_INTERPRETER[0]; comm[1] = COMMAND_INTERPRETER[1]; comm[2] = command; long start = System.currentTimeMillis(); try { // Start process Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir)); // Get input and error streams BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream()); BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream()); boolean end = false; while (!end) { int c = 0; while ((ls_err.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_err.read())); } c = 0; while ((ls_in.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_in.read())); } try { ls_proc.exitValue(); // if the process has not finished, an exception is thrown // else while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read())); while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read())); end = true; } catch (IllegalThreadStateException ex) { // Process is running } // The process is not allowed to run longer than given time. if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { ls_proc.destroy(); end = true; ret.append("!!!! Process has timed out, destroyed !!!!!"); } try { Thread.sleep(50); } catch (InterruptedException ie) { } } } catch (IOException e) { ret.append("Error: " + e); } return ret.toString(); }
/** * Gives the same basic functionality of File.exists but can be used to look for removable media * without showing a system dialog if the media is not present. Workaround pulled from the <A * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start * requiring Java 6. */ protected static boolean fileExists(File file) { try { Process process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()}); // We need to consume all available output or the process will block. boolean haveExitCode = false; int exitCode = -1; InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); while (!haveExitCode) { while (out.read() >= 0) {} while (err.read() >= 0) {} try { exitCode = process.exitValue(); haveExitCode = true; } catch (IllegalThreadStateException e) { // Not yet complete. Thread.sleep(100); } } // int exitCode = process.waitFor(); return exitCode == 0; } catch (IOException e) { System.out.println("Unable to check for file: " + file + " : " + e); return false; } catch (InterruptedException e) { System.out.println("Unable to check for file. Interrupted: " + file + " : " + e); return false; } }
protected boolean compile(String fileName) { String compiler = "javac"; String classpathOption = "-classpath"; if (jikes != null) { compiler = jikes; classpathOption = "-bootclasspath"; } String[] args = new String[] { compiler, "-d", tmpdir, classpathOption, tmpdir + pathSep + CLASSPATH, tmpdir + "/" + fileName }; String cmdLine = compiler + " -d " + tmpdir + " " + classpathOption + " " + tmpdir + pathSep + CLASSPATH + " " + fileName; // System.out.println("compile: "+cmdLine); File outputDir = new File(tmpdir); try { Process process = Runtime.getRuntime().exec(args, null, outputDir); StreamVacuum stdout = new StreamVacuum(process.getInputStream()); StreamVacuum stderr = new StreamVacuum(process.getErrorStream()); stdout.start(); stderr.start(); process.waitFor(); stdout.join(); stderr.join(); if (stdout.toString().length() > 0) { System.err.println("compile stdout from: " + cmdLine); System.err.println(stdout); } if (stderr.toString().length() > 0) { System.err.println("compile stderr from: " + cmdLine); System.err.println(stderr); } int ret = process.exitValue(); return ret == 0; } catch (Exception e) { System.err.println("can't exec compilation"); e.printStackTrace(System.err); return false; } }
static int exec(String line, boolean showOutput, File dir) throws Exception { Process process = null; if (showOutput) { System.out.println("exec: " + line); } process = Runtime.getRuntime().exec("cmd /c " + line, null, dir); InputStream stdin = process.getInputStream(); InputStream stderr = process.getErrorStream(); StreamGobbler stdinGobbler = new StreamGobbler(stdin, "stdin: "); StreamGobbler stderrGobbler = new StreamGobbler(stderr, "stderr: "); stdinGobbler.start(); stderrGobbler.start(); process.waitFor(); if (showOutput) { System.out.println("exec \"" + line + "\" returned " + process.exitValue()); } return process.exitValue(); }
public static int ensureNTServiceIsRunning(String serviceName, String service) throws Exception { ArrayList<String> serviceList = getRunningNTServices(); if (serviceList == null) return -1; // not NT kernel? for (String svc : serviceList) { if (serviceName.equals(svc.trim())) return 0; // service already running } Process process = RUNTIME.exec(comSpec + "net start \"" + service + "\""); process.waitFor(); // wait for the process to complete int rc = process.exitValue(); // pick up its return code boolean success = (rc == 0); if (success) System.out.println("Successfully started service '" + serviceName + "'."); return (success ? 1 : -1); }
void executeStormClass( String className, String jvmType, List<String> jvmOptions, List<String> extraJars, List<String> args, boolean fork, boolean daemon, String daemonName) { List<String> extraPaths = new ArrayList<>(); extraPaths.add(this.clusterConfDirectory); String stormLogDirectory = this.confValue("storm.log.dir", extraPaths, daemon); if ((stormLogDirectory == null) || ("".equals(stormLogDirectory)) || ("nil".equals(stormLogDirectory))) { stormLogDirectory = this.stormHomeDirectory + this.fileSeparator + "logs"; } List<String> commandList = new ArrayList<String>(); commandList.add(this.javaCommand); commandList.add(jvmType); commandList.add("-Ddaemon.name=" + daemonName); commandList.add(this.getConfigOptions()); commandList.add("-Dstorm.home=" + this.stormHomeDirectory); commandList.add("-Dstorm.log.dir=" + stormLogDirectory); commandList.add( "-Djava.library.path=" + this.confValue("java.library.path", extraJars, daemon)); commandList.add("-Dstorm.conf.file=" + this.configFile); commandList.add("-cp"); commandList.add(this.getClassPath(extraJars, daemon)); commandList.addAll(jvmOptions); commandList.add(className); commandList.addAll(args); ProcessBuilder processBuilder = new ProcessBuilder(commandList); processBuilder.inheritIO(); try { Process process = processBuilder.start(); System.out.println("Executing the command: "); String commandLine = StringUtils.join(commandList, " "); System.out.println(commandLine); if (daemon == true) { Runtime.getRuntime().addShutdownHook(new ShutdownHookThread(process, commandLine)); } System.out.println("Waiting for subprocess to finish"); process.waitFor(); System.out.println("subprocess finished"); System.out.println("Exit value from subprocess is :" + process.exitValue()); } catch (Exception ex) { System.out.println( "Exception occured while starting process via " + "processbuilder " + ex.getMessage()); } }
/* * Run the given command. */ protected static int run(String message, String[] commandArray) { try { Process process = Runtime.getRuntime().exec(commandArray, null, output); StreamProcessor.start(process.getErrorStream(), StreamProcessor.STDERR, true); StreamProcessor.start(process.getInputStream(), StreamProcessor.STDOUT, true); process.waitFor(); return process.exitValue(); } catch (IOException e) { fail(message, e); } catch (InterruptedException e) { fail(message, e); } return -1; }
/** * Hook method called by the super-class if the server enters unexpected state. This method * destroys the server process and changes state to disabled. */ protected void handleUnexpectedState(Boolean stateChanged) { if (mProcess != null) { try { mProcess.exitValue(); // the process has already exitted, try to restart it changeState(STATE_START_DEPENDENCIES); } catch (IllegalThreadStateException itse) { // the process is still running, so kill it mProcess.destroy(); } } else { setDisabled(true); changeState(STATE_DISABLED); } }
static void realMain(String[] args) throws Throwable { // jmap doesn't work on Windows if (System.getProperty("os.name").startsWith("Windows")) return; final String childClassName = Job.class.getName(); final String classToCheckForLeaks = Job.classToCheckForLeaks(); final String uniqueID = String.valueOf(new Random().nextInt(Integer.MAX_VALUE)); final String[] jobCmd = { java, "-Xmx8m", "-classpath", System.getProperty("test.classes", "."), childClassName, uniqueID }; final Process p = new ProcessBuilder(jobCmd).start(); final String childPid = match( commandOutputOf(jps, "-m"), "(?m)^ *([0-9]+) +\\Q" + childClassName + "\\E *" + uniqueID + "$", 1); final int n0 = objectsInUse(p, childPid, classToCheckForLeaks); final int n1 = objectsInUse(p, childPid, classToCheckForLeaks); equal(p.waitFor(), 0); equal(p.exitValue(), 0); failed += p.exitValue(); // Check that no objects were leaked. System.out.printf("%d -> %d%n", n0, n1); check(Math.abs(n1 - n0) < 2); // Almost always n0 == n1 check(n1 < 20); drainers.shutdown(); }
private static int readInt(Scanner s, Process process) throws ExecutionException { long started = System.currentTimeMillis(); while (System.currentTimeMillis() - started < PORTS_WAITING_TIMEOUT) { if (s.hasNextLine()) { String line = s.nextLine(); try { return Integer.parseInt(line); } catch (NumberFormatException ignored) { continue; } } try { Thread.sleep(200); } catch (InterruptedException ignored) { } if (process.exitValue() != 0) { String error; try { error = "Console process terminated with error:\n" + StreamUtil.readText(process.getErrorStream()); } catch (Exception ignored) { error = "Console process terminated with exit code " + process.exitValue(); } throw new ExecutionException(error); } else { break; } } throw new ExecutionException("Couldn't read integer value from stream"); }
static String outputOf(final Process p) { try { Future<String> outputFuture = futureOutputOf(p.getInputStream()); Future<String> errorFuture = futureOutputOf(p.getErrorStream()); final String output = outputFuture.get(); final String error = errorFuture.get(); // Check for successful process completion equal(error, ""); equal(p.waitFor(), 0); equal(p.exitValue(), 0); return output; } catch (Throwable t) { unexpected(t); throw new Error(t); } }
/** * Checks if address can be reached using one argument InetAddress.isReachable() version or ping * command if failed. * * @param addr Address to check. * @param reachTimeout Timeout for the check. * @return {@code True} if address is reachable. */ public static boolean reachableByPing(InetAddress addr, int reachTimeout) { try { if (addr.isReachable(reachTimeout)) return true; String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress()); Process myProc = Runtime.getRuntime().exec(cmd); myProc.waitFor(); return myProc.exitValue() == 0; } catch (IOException ignore) { return false; } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); return false; } }
public int compileJavaProgram(JavaProgram jp, String writeDirectory, String classpath) throws Exception { if (!jp.isTypeResolved()) { System.out.println( "Compilation will not take place since there were type resolution errors."); return -1; } String fileList = jp.getFilesAsString(); String command = "javac -d " + writeDirectory + " -classpath " + classpath + " " + fileList; // System.out.println(command); System.out.print("Compiling..."); Process p = Runtime.getRuntime().exec(command); // need to squirt the output into the InputStream is = p.getErrorStream(); Util.read(is, "compiler"); // blocks here int exitValue = p.exitValue(); return exitValue; }
public static int executeCommand(String completeCommand, PrintWriter out) { try { Process p = Runtime.getRuntime().exec(completeCommand); if (out != null) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = in.readLine(); while (line != null) { out.println(line); line = in.readLine(); } in.close(); out.flush(); } p.waitFor(); int status = p.exitValue(); p.destroy(); return status; } catch (Exception e) { e.printStackTrace(); System.exit(1); return -1; } }
private void doCompile(@NotNull final ModuleChunk chunk, @NotNull String outputDir) throws IOException { myCompileContext.getProgressIndicator().checkCanceled(); if (ApplicationManager.getApplication() .runReadAction( new Computable<Boolean>() { public Boolean compute() { return chunk.getFilesToCompile().isEmpty() ? Boolean.TRUE : Boolean.FALSE; } }) .booleanValue()) { return; // should not invoke javac with empty sources list } int exitValue = 0; try { final Process process = myCompiler.launchProcess(chunk, outputDir, myCompileContext); final long compilationStart = System.currentTimeMillis(); final ClassParsingThread classParsingThread = new ClassParsingThread(isJdk6(JavaSdkUtil.getSdkForCompilation(chunk)), outputDir); final Future<?> classParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(classParsingThread); OutputParser errorParser = myCompiler.createErrorParser(outputDir, process); CompilerParsingThread errorParsingThread = errorParser == null ? null : new SynchedCompilerParsing( process, myCompileContext, errorParser, classParsingThread, true, errorParser.isTrimLines()); Future<?> errorParsingThreadFuture = null; if (errorParsingThread != null) { errorParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(errorParsingThread); } OutputParser outputParser = myCompiler.createOutputParser(outputDir); CompilerParsingThread outputParsingThread = outputParser == null ? null : new SynchedCompilerParsing( process, myCompileContext, outputParser, classParsingThread, false, outputParser.isTrimLines()); Future<?> outputParsingThreadFuture = null; if (outputParsingThread != null) { outputParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(outputParsingThread); } try { exitValue = process.waitFor(); } catch (InterruptedException e) { process.destroy(); exitValue = process.exitValue(); } catch (Error e) { process.destroy(); exitValue = process.exitValue(); throw e; } finally { if (CompileDriver.ourDebugMode) { System.out.println("Compiler exit code is " + exitValue); } if (errorParsingThread != null) { errorParsingThread.setProcessTerminated(true); } if (outputParsingThread != null) { outputParsingThread.setProcessTerminated(true); } joinThread(errorParsingThreadFuture); joinThread(outputParsingThreadFuture); classParsingThread.stopParsing(); joinThread(classParsingThreadFuture); registerParsingException(outputParsingThread); registerParsingException(errorParsingThread); assert outputParsingThread == null || !outputParsingThread.processing; assert errorParsingThread == null || !errorParsingThread.processing; assert classParsingThread == null || !classParsingThread.processing; } } finally { compileFinished(exitValue, chunk, outputDir); myModuleName = null; } }
public static void main(String args[]) { int PC, SP, IR, AC, X, Y; int[] memory = new int[1000]; SP = IR = AC = X = Y = 0; PC = -1; // Gets "MainMemory" class from working directory. String directory = System.getProperty("user.dir") + "\\bin\\ MainMemory"; Scanner in = new Scanner(System.in); try { int x, y, index = 0; String z = ""; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("java -cp " + directory); // Process proc = rt.exec("cat Hello.java"); InputStream os = proc.getInputStream(); IR = 0; // GRABS INSTRUCTION OUT OF STREAM while ((x = os.read()) != -1) { try { if (x > 47 && x < 58) { y = Character.getNumericValue(x); z += y; } else if (x == 10 && z != "") { x = Integer.parseInt(z); y = 0; z = ""; // System.out.println(x); memory[index] = x; index++; } else if (x == 13) { break; } } catch (Exception e) { System.out.println("ERROR: Error while reading instructions."); System.exit(1); } } // PERFORMS INSTRUCTIONS for (int k = 0; k < index; k++) { // System.out.println(k + " == " + memory[k]); IR = memory[k]; switch (IR) { case 1: // System.out.println("LOAD VALUE"); //READS IN THE VALUE PC++; k++; AC = memory[k]; PC++; break; case 2: // System.out.println("LOAD ADDR"); //READS VALUE FROM AN ADDRESS PC++; AC = memory[memory[k + 1]]; k++; break; case 3: // System.out.println("STORE ADDR"); //WRITES THE VALUE OF AC TO THE ADDRESS PC++; memory[memory[k + 1]] = AC; k++; try { File file = new File(System.getProperty("user.dir") + "\\src\\program.txt"); FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); for (int i = 0; i < index; i++) { out.write("" + memory[i]); out.newLine(); } out.flush(); out.close(); } catch (IOException e) { System.out.println("ERROR: Could not rewrite program"); } break; case 4: // System.out.println("ADD X"); //ADDS X TO AC PC++; AC += X; break; case 5: // System.out.println("ADD Y"); //ADDS Y TO AC PC++; AC += Y; break; case 6: // System.out.println("SUB X"); //SUBSTRACTS X FROM AC PC++; AC -= X; break; case 7: // System.out.println("SUB Y"); //SUBTRACTS Y FROM AC PC++; AC -= Y; break; case 8: // System.out.println("GET PORT"); //RECEIVES EITHER INTEGER OR CHARACTER DEPENDING ON // PORT NUMBER, 1 OR 2 PC++; k++; if (memory[k] == 1) { PC++; // System.out.println("PORT = READ INT"); //RECEIVES INTEGER FROM USER AND PLACES IT // INTO AC AC = in.nextInt(); } else if (memory[k] == 2) // RECEIVES CHARACTER FROM USER AND PLACES IT INTO AC { PC++; // System.out.println("PORT = READ CHAR"); AC = (int) in.next(".{1}").charAt(0); } break; case 9: // System.out.println("PUT PORT"); //PRINTS EITHER INTEGER OR CHARACTER DEPENDING ON // PORT NUMBER, 1 OR 2 PC++; k++; if (memory[k] == 1) { // System.out.println("PORT = WRITE INT"); PRINTS OUT INTEGER VALUE FROM AC PC++; System.out.print(AC); } else if (memory[k] == 2) { // System.out.println("PORT = WRITE CHAR"); //PRINTS OUT CHARACTER VALUE FROM AC PC++; System.out.print((char) AC); } break; case 10: // System.out.println("COPYTO X"); //COPIES VALUE FROM X INTO AC PC++; X = AC; break; case 11: // System.out.println("COPYTO Y"); //COPIES VALUE FROM Y INTO AC PC++; Y = AC; break; case 12: // System.out.println("COPYFROM X"); //COPIES VALUE FROM X INTO AC PC++; AC = X; break; case 13: // System.out.println("COPYFROM Y"); //COPIES VALUE FROM Y INTO AC PC++; AC = Y; break; case 14: // System.out.println("JUMP ADDR"); //JUMPS TO AN ADDRESS PC++; k = memory[k + 1] - 1; break; case 15: // System.out.println("JUMPIFEQUAL ADDR"); //JUMPS TO AN ADDRESS IF AC IS EQUAL TO ZERO PC++; if (AC == 0) { PC++; k = memory[k + 1] - 1; } else { PC++; k++; } break; case 16: // System.out.println("JUMPIFNOTEQUAL ADDR"); //JUMPS TO AN ADDRESS IF AC IS NOT EQUAL // TO ZERO PC++; if (AC != 0) { PC++; k = memory[k + 1] - 1; } else { PC++; k++; } break; case 17: // System.out.println("CALL ADDR"); // PUSH RETURN ADDRESS INTO STACK, AND JUMPS AN // ADDRESS PC++; SP = PC; k = memory[k + 1] - 1; PC++; break; case 18: // System.out.println("RETURN"); //POPS RETURN ADDRESS FROM STACK, AND JUMPS TO IT PC++; k = SP + 1; break; case 19: // System.out.println("INC X"); //INCREMENTS VALUE IN X BY ONE PC++; X++; break; case 20: // System.out.println("DEC X"); //DECREMENTS VALUE IN X BY ONE PC++; X--; break; case 30: // System.out.println("END"); //ENDS PROCESS PC++; X = 0; Y = 0; AC = 0; k = index; try { os.close(); } catch (Exception e) { } break; } // System.out.println("\nProgram Counter: " + PC); } // PROCESS ENDS proc.waitFor(); in.close(); int exitVal = proc.exitValue(); System.out.println("\nProcess exited: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } System.exit(1); }
/** * Reads the next line from the process. This method will be used only if the supporting Java * Native Interface library could not be loaded. */ private synchronized String pure_readLine() { String line; long current, timeout = ((new Date()).getTime()) + threshold; if (null == p || null == in || null == err) return null; // Debug.verbose("P4Process.readLine()"); try { for (; ; ) { if (null == p || null == in || null == err) { Debug.error("P4Process.readLine(): Something went null"); return null; } current = (new Date()).getTime(); if (current >= timeout) { Debug.error("P4Process.readLine(): Timeout"); // If this was generating a new object from stdin, return an // empty string. Otherwise, return null. for (int i = 0; i < new_cmd.length; i++) { if (new_cmd[i].equals("-i")) return ""; } return null; } // Debug.verbose("P4Process.readLine().in: "+in); try { /** * If there's something coming in from stdin, return it. We assume that the p4 command was * called with -s which sends all messages to standard out pre-pended with a string that * indicates what kind of messsage it is error warning text info exit */ // Some errors still come in on Standard error while (err.ready()) { line = err.readLine(); if (null != line) { addP4Error(line + "\n"); } } if (in.ready()) { line = in.readLine(); Debug.verbose("From P4:" + line); if (line.startsWith("error")) { if (!line.trim().equals("") && (-1 == line.indexOf("up-to-date")) && (-1 == line.indexOf("no file(s) to resolve"))) { addP4Error(line); } } else if (line.startsWith("warning")) { } else if (line.startsWith("text")) { } else if (line.startsWith("info")) { } else if (line.startsWith("exit")) { int exit_code = new Integer(line.substring(line.indexOf(" ") + 1, line.length())).intValue(); if (0 == exit_code) { Debug.verbose("P4 Exec Complete."); } else { Debug.error("P4 exited with an Error!"); } return null; } if (!raw) line = line.substring(line.indexOf(":") + 1).trim(); Debug.verbose("P4Process.readLine(): " + line); return line; } } catch (NullPointerException ne) { } // If there's nothing on stdin or stderr, check to see if the // process has exited. If it has, return null. try { exit_code = p.exitValue(); return null; } catch (IllegalThreadStateException ie) { Debug.verbose("P4Process: Thread is not done yet."); } // Sleep for a second, so this thread can't become a CPU hog. try { Debug.verbose("P4Process: Sleeping..."); Thread.sleep(100); // Sleep for 1/10th of a second. } catch (InterruptedException ie) { } } } catch (IOException ex) { return null; } }