/** * Spawn an OS subprocess. Follows the Oracle-recommended method of * using ProcessBuilder rather than Runtime.exec(), and includes some * safeguards to prevent blocked and stale processes. A thread is * created that will perform the spawn, consume its output and error * streams (to prevent blocking due to full buffers), then clean up. * * @param cmd The cmd/arg list for execution */ static public void spawnProcess(final List<String> cmd) { if (cmd == null) return; Thread t = new Thread() { public void run() { Process proc = null; proc = startProcess(cmd, true); if (proc != null) { consumeProcessOutput(proc); try { proc.waitFor(); } catch (InterruptedException e) { // ignore (we terminate anyway) } destroyProcess(proc); } Thread.currentThread().interrupt(); } }; t.setDaemon(true); t.start(); }
/** * Start a new process. * * @param cmd The cmd/arg list for execution * @param merge True to merge the process's error stream into its * output stream * @return The new Process, or null upon failure */ static private Process startProcess(List<String> cmd, boolean merge) { if (cmd == null) return null; ProcessBuilder pb = new ProcessBuilder(cmd); if (merge) pb = pb.redirectErrorStream(true); Process proc = null; try { proc = pb.start(); } catch(IOException e) { e.printStackTrace(); } return proc; }
/** * Destroy a Process, first attempting to close its I/O streams. * * @param p The Process to destroy */ static private void destroyProcess(Process p) { if (p == null) return; InputStream stdout = p.getInputStream(); InputStream stderr = p.getErrorStream(); OutputStream stdin = p.getOutputStream(); try { if (stdout != null) stdout.close(); if (stderr != null) stderr.close(); if (stdin != null) stdin.close(); } catch(IOException e) { e.printStackTrace(); } p.destroy(); }
private boolean installrootfs_priv(String from, String target) { try { Runtime runtime = Runtime.getRuntime(); String[] envp = {"BUSYBOX=/data/data/org.Ex3.AndLinux/files/utils/busybox", "SRC=" + from, "TGT=" + target}; int ret; Process process = runtime.exec("/data/data/org.Ex3.AndLinux/files/utils/install.sh", envp); if ((ret = process.waitFor()) != 0) { Log.d("install", String.valueOf(ret)); ToastUtils.showText(this, getString(R.string.error), Toast.LENGTH_LONG); return false; } } catch (Throwable ob) { ob.printStackTrace(); ToastUtils.showText(this, ob.getMessage(), Toast.LENGTH_LONG); return false; } ToastUtils.showText(this, getString(R.string.success), Toast.LENGTH_LONG); return true; }
@VisibleForTesting static FileDescriptorFactory create(String address, String... cmd) throws IOException { // must be created before the process final LocalServerSocket socket = new LocalServerSocket(address); try { final Process shell = new ProcessBuilder(cmd) .redirectErrorStream(true) .start(); final FileDescriptorFactory result = new FileDescriptorFactory(shell, socket); result.startServer(); return result; } catch (Throwable t) { shut(socket); throw t; } }
public static byte[] exec(String workDir, String[] evnp, String... cmd) { try { Process process = Runtime.getRuntime().exec(cmd, evnp, TextUtils.isEmpty(workDir) ? null : new File(workDir)); InputStream inputStream = process.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buf = new byte[8096]; int c = inputStream.read(buf); while (c != -1) { byteArrayOutputStream.write(buf, 0, c); c = inputStream.read(buf); } return byteArrayOutputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }
private String calcBranch() { try { Process p = new ProcessBuilder("git", "branch").start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = br.readLine(); while (line != null) { if (!line.startsWith("*")) { line = br.readLine(); continue; } String branch = line.substring(2); return branch; } return "(unknown)"; } catch (Exception e) { return "(unknown)"; } }
private String calcDescribe() { try { Process p = new ProcessBuilder("git", "describe", "--always", "--dirty").start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = br.readLine(); return line; } catch (Exception e) { return "(unknown)"; } }
protected String doInBackground(Void... params) { Runtime rt = Runtime.getRuntime(); try{ Process proc = rt.exec("/system/xbin/bash " + scriptdir + "testdebug.sh"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (line.equals("ENABLED") || line.equals("RECOVERY") || line.equals("DISABLED")){ System.out.println(line); return line; } } } catch (Exception e){ e.printStackTrace(); } return "fail"; }
protected String doInBackground(Void... params) { Runtime rt = Runtime.getRuntime(); try{ Process proc = rt.exec("/system/xbin/bash " + scriptdir + "installAnti.sh"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (line.equals("0")){ System.out.println(line); return line; } return line; } } catch (Exception e){ e.printStackTrace(); } return "fail"; }
protected String doInBackground(Void... params) { Runtime rt = Runtime.getRuntime(); try{ Process proc = rt.exec("/system/xbin/bash " + scriptdir + "testroot.sh"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (line.equals("0") || line.equals("1") || line.equals("2")){ System.out.println(line); return line; } return line; } } catch (Exception e){ e.printStackTrace(); } return "fail"; }
protected String doInBackground(Void... params) { Runtime rt = Runtime.getRuntime(); try{ Process proc = rt.exec("/system/xbin/bash " + scriptdir + "getgesture.sh"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); return line; } } catch (Exception e){ e.printStackTrace(); } return "fail"; }
public void generatePolicyToken(String presentationPolicyDest) { StringWriter sw = new StringWriter(); sw.write(this.serialPolicy); try { FileWriter fw = new FileWriter(presentationPolicyDest); fw.write(sw.toString()); fw.close(); Process pr = Runtime.getRuntime().exec(this.generationScript, null, new File(this.generationScriptPath)); } catch (Exception e) { e.printStackTrace(); } }
private void runRsync(String source, String destination, List<String> options) throws Exception { ArrayList<String> argv = new ArrayList<String>(options); String line; Process process; BufferedReader processOutput, processErrors; argv.add(0, "rsync"); argv.add(source); argv.add(destination); process = Runtime.getRuntime().exec(argv.toArray(new String[0])); processOutput = new BufferedReader(new InputStreamReader(process.getInputStream())); processErrors = new BufferedReader(new InputStreamReader(process.getErrorStream())); do { line = processOutput.readLine(); if (line != null) System.out.println(line); } while (line != null); do { line = processErrors.readLine(); if (line != null) System.out.println(line); } while (line != null); process.waitFor(); }
public static boolean getAdbdStatus() { int lineCount = 0; try { Process process = Runtime.getRuntime().exec("ps | grep adbd"); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String str = input.readLine(); while (str != null) { lineCount++; str = input.readLine(); } if (lineCount >= 2) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; }
public static boolean setAdbWifiStatus(boolean status) { Process p; try { p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); os.writeBytes("setprop service.adb.tcp.port " + String.valueOf(getPort()) + "\n"); os.writeBytes("stop adbd\n"); if (status) { os.writeBytes("start adbd\n"); } os.writeBytes("exit\n"); os.flush(); p.waitFor(); if (p.exitValue() != 255) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
public void ok(View v) { text=(TextView)findViewById(R.id.text); EditText shell=(EditText)findViewById(R.id.shell); //获取文本框文本 String q=""; q=shell.getText().toString(); if (shell.getText().toString().length() < 0 /*大于0位数字*/ || shell.getText().toString().length() > 0 /*小于0位数字*/ ) { Runtime mRuntime = Runtime.getRuntime(); try { //Process中封装了返回的结果和执行错误的结果 Process mProcess = mRuntime.exec(""+q); BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream())); StringBuffer mRespBuff = new StringBuffer(); char[] buff = new char[1024]; int ch = 0; while((ch = mReader.read(buff)) != -1){ mRespBuff.append(buff, 0, ch); } mReader.close(); text.setText(mRespBuff.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();} } else{ Snackbar("请不要输入空气!","确定"); } }
public void clearRecording() { log.info("USER {}: END recording in room {}", name, roomName); recorderCaller.stop(); recorderCaller.release(); // conversion log.info("should run {}", pendingConversion); if (pendingConversion == true) { log.info("Run Conversion"); new Thread(new Runnable() { public void run(){ try { log.info("Running: {}", "ffmpeg -i " + RECORDING_PATH + preConvertedName + RECORDING_EXT + " -strict -2 -q:vscale 0 " + RECORDING_PATH + preConvertedName + ".mp4"); Process proc = Runtime.getRuntime().exec("ffmpeg -i " + RECORDING_PATH + preConvertedName + RECORDING_EXT + " -strict -2 -q:vscale 0 " + RECORDING_PATH + preConvertedName + ".mp4"); proc.waitFor(); log.info("Running: {}", "ffmpeg -i " + RECORDING_PATH + preConvertedName + ".mp4 -profile:v baseline -level 3.0 -s 1280x960 -start_number 0 -hls_time 10 -hls_list_size 0 -strict -2 -f hls " + RECORDING_PATH + preConvertedName +".m3u8"); Runtime.getRuntime().exec("ffmpeg -i " + RECORDING_PATH + preConvertedName + ".mp4 -profile:v baseline -level 3.0 -s 1280x960 -start_number 0 -hls_time 10 -hls_list_size 0 -strict -2 -f hls " + RECORDING_PATH + preConvertedName +".m3u8"); } catch (IOException e) { log.info(e.getMessage()); } catch (InterruptedException ie) { log.info(ie.getMessage()); } } }).start(); } pendingConversion = false; }
@RequestMapping("/iniciar-servidor") public Pc greeting() { DB db = new DB(); db.conectar(); Pc usuario = db.insertar(); db.desconectar(); if (Util.docker) { try{ Process proceso; Runtime shell = Runtime.getRuntime(); // COMANDO DOCKER // docker run -d --rm -p [PuertoPHP]:80 -p [PuertoSQL]:3306 --name=server[ID] xxdrackleroxx/test proceso = shell.exec("docker run -d --rm -p " + usuario.getPuertoPHP() + ":80 -p " + usuario.getPuertoSQL() + ":3306 --name=server" + usuario.getId() + " xxdrackleroxx/test"); proceso.waitFor(); }catch(Exception e){ System.out.println("[ERROR] Problema con shell"); } } return usuario; }
@RequestMapping("/detener-servidor") public String greeting(@RequestParam(value="id", defaultValue="-1") Integer id) { if(id != -1){ DB db = new DB(); db.conectar(); db.eliminar(id); db.desconectar(); if (Util.docker) { Process proceso; Runtime shell = Runtime.getRuntime(); try { // COMANDO DOCKER // docker run -d --rm -p [PuertoPHP]:80 -p [PuertoSQL]:3306 --name=server[ID] xxdrackleroxx/test:1.0 proceso = shell.exec("docker stop -t 0 server" + id); } catch (Exception e) { return "{\"status\":\"ERROR SHELL\"}"; } } return "{\"status\":\"OK\"}"; } return "{\"status\":\"ERROR ID\"}"; }
/** * Runs MXBeanWeirdParamTest$ClientSide with the passed options and redirects * subprocess standard I/O to the current (parent) process. This provides a * trace of what happens in the subprocess while it is runnning (and before * it terminates). * * @param serviceUrlStr string representing the JMX service Url to connect to. */ private int runClientSide(String serviceUrlStr) throws Exception { // Building command-line List<String> opts = buildCommandLine(); opts.add(serviceUrlStr); // Launch separate JVM subprocess int exitCode = 0; String[] optsArray = opts.toArray(new String[0]); ProcessBuilder pb = new ProcessBuilder(optsArray); Process p = ProcessTools.startProcess("MXBeanWeirdParamTest$ClientSide", pb); // Handling end of subprocess try { exitCode = p.waitFor(); if (exitCode != 0) { System.out.println( "Subprocess unexpected exit value of [" + exitCode + "]. Expected 0.\n"); } } catch (InterruptedException e) { System.out.println("Parent process interrupted with exception : \n " + e + " :" ); // Parent thread unknown state, killing subprocess. p.destroyForcibly(); throw new RuntimeException( "Parent process interrupted with exception : \n " + e + " :" ); } finally { return exitCode; } }
/** * Resolve address * @param binary The binary * @param address The address * @return The resolved address */ private static String resolveAddress(String binary, String address) throws Exception { int offset = address.indexOf("+0x"); if (offset != -1) { String function = address.substring(0, offset); List<String> command = new ArrayList<>(); command.add("eu-addr2line"); command.add("-e"); command.add(binary); command.add(address); ProcessBuilder pb = new ProcessBuilder(command); Process p = pb.start(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = p.getInputStream(); int c = is.read(); while (c != -1) { baos.write(c); c = is.read(); } is.close(); p.waitFor(); String output = baos.toString(); if (output.startsWith("/")) { return function + "|" + output.substring(output.lastIndexOf("/") + 1, output.length() - 1); } } return address; }
private static void runtool(jvm jvm, String loc, String[] args) throws IOException { System.out.println(concatenate(args) + ':'); if (jvm == null) { com.pivotal.gemfirexd.internal.iapi.tools.run.main(args); return; } Vector cmd = jvm.getCommandLine(); cmd.addElement("-jar"); cmd.addElement(loc); for (int i=0; i < args.length; i++) { cmd.addElement(args[i]); } String command = concatenate((String[]) cmd.toArray(new String[0])); Process pr = null; try { pr = Runtime.getRuntime().exec(command); BackgroundStreamSaver saver = new BackgroundStreamSaver(pr.getInputStream(), System.out); saver.finish(); pr.waitFor(); pr.destroy(); } catch(Throwable t) { System.out.println("Process exception: " + t.getMessage()); if (pr != null) { pr.destroy(); pr = null; } } }
/** * Consume a process's output stream until EOS is reached. * If this method is being used to prevent process blocking due to * full output buffers, then it is recommended that the process be * created with its error stream merged into its output stream, * otherwise blocking can still occur due to a full error stream * buffer. * * @param p The Process whose output stream to consume */ static private void consumeProcessOutput(Process p) { if (p == null) return; InputStream output = p.getInputStream(); try { while (output.read() != -1) { // NOP } } catch(IOException e) { e.printStackTrace(); } }
private static void shut(Process proc) { try { if (proc != null) { shut(proc.getInputStream()); shut(proc.getOutputStream()); proc.destroy(); } } catch (Exception e) { // just as planned } }
/** * Utility for taking a main class, executing it as a process, * and returning a scanner of that process stdout. * Callers takes ownership of returned Scanner and should close() the scanner when done. */ public static Scanner getCommandOutput(Class<?> childMain, String[] args) { OutputScanner outputScanner = new OutputScanner(); OutputStream outputStream = outputScanner.getOutputStream(); Scanner scan = outputScanner.getScanner(); scan.useDelimiter(System.getProperty("line.separator")); try { Process p = spawnChildProcess(childMain, args, null, outputStream, null); waitForAndDestroy(p); } catch (IOException e) { e.printStackTrace(); } return scan; }
private String calcLastCommitHash() { try { Process p = new ProcessBuilder("git", "log", "-1", "--format=%H").start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = br.readLine(); return line; } catch (Exception e) { return "(unknown)"; } }
private String readSystemFile(final String pSystemFile) { String content = ""; InputStream in = null; try { final Process process = new ProcessBuilder(new String[] { "/system/bin/cat", pSystemFile }).start(); in = process.getInputStream(); content = readFully(in); } catch (final Exception e) { } return content; }
protected String doInBackground(Void... params) { if (hasRoot == 1){ scriptname = "removelock.sh"; } else if (hasRoot == 2){ scriptname = "removelockesc.sh"; } Runtime rt = Runtime.getRuntime(); try{ Process proc = rt.exec("/system/xbin/bash " + scriptdir + scriptname); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (line.equals("0")){ System.out.println(line); return line; } return line; } } catch (Exception e){ e.printStackTrace(); } return "fail"; }
@Override public void execute() { try { Process pr = Runtime.getRuntime().exec(userWebServiceName, null, new File(userWebServicePath)); } catch (Exception e) { logger.error("Failed to load the user's webservice.", e); } }