private Integer startTunnelSSH(Instance instance) throws InterruptedException { Instance tunnelInstance = runningInstances(tunnelResourceId).get(0); Integer localPort = Double.valueOf(Randoms.number(3000, 10000)).intValue(); CountDownLatch latch = new CountDownLatch(1); Thread tunnelThread = new Thread( () -> { Process process = null; try { Path keyPath = KeyPair.keyFile(tunnelInstance.getKeyName(), env); String userAndHost = "ubuntu@" + hostName(tunnelInstance); String portBinding = Strings.format("{}:{}:22", localPort, instance.getPrivateIpAddress()); List<String> command = tunnelCommand(keyPath, userAndHost, portBinding); logger.info("tunnel command => {}", String.join(" ", command)); process = new ProcessBuilder().command(command).start(); process.getInputStream().read(); // wait until there is output latch.countDown(); process.waitFor(); } catch (InterruptedException | IOException e) { throw new IllegalStateException(e); } finally { if (process != null) process.destroy(); } }); tunnelThread.setDaemon(true); tunnelThread.start(); latch.await(); return localPort; }
public static String getArchName() throws Exception { if (archName == null) { archName = "lin"; // bits Process process = Runtime.getRuntime().exec("uname -m"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error arch"); BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String arch = inStream.readLine(); if (arch.equals("i686")) archName += "32"; else archName += "64"; process.destroy(); // SSE process = Runtime.getRuntime().exec("cat /proc/cpuinfo"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo"); inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String line, cpuinfo = ""; while ((line = inStream.readLine()) != null) cpuinfo += line; String bestSSE = "sse"; String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"}; for (int i = 0; i < sses.length; i++) { if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i]; } archName += bestSSE; process.destroy(); } return archName; }
@Override public void stop() { stopping = true; try { // A newline is interpreted by the replica client as a sign to stop. os.write('\n'); os.flush(); } catch (IOException e) { process.destroy(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); flushFileOut(); System.exit(1); } try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); } flushFileOut(); }
private void installOnMac(File location) throws IOException, ZipException, InterruptedException { File installDir = new File(location + "/adb_tools.zip"); if (!installDir.exists()) { installDir.getParentFile().mkdirs(); InputStream input = this.getClass().getResourceAsStream("/JDroidLib/res/adb_tools/adb-mac.zip"); File adb_tools = new File(location + "/adb_tools.zip"); OutputStream output = new FileOutputStream(adb_tools); int readBytes = 0; byte[] buffer = new byte[4096]; while ((readBytes = input.read(buffer)) > 0) { output.write(buffer, 0, readBytes); } input.close(); output.close(); ZipFile zip = new ZipFile(adb_tools); zip.extractAll(location.toString()); ProcessBuilder process = new ProcessBuilder("chmod", "a+x", location + "/adb"); Process pr = process.start(); Thread.sleep(200); pr.destroy(); process = new ProcessBuilder("chmod", "a+x", location + "/fastboot"); pr = process.start(); Thread.sleep(200); pr.destroy(); adb_tools.delete(); } }
@Test public void testMasterSwitchHappensOnKillMinus9() throws Exception { Process proc = null; HighlyAvailableGraphDatabase dbWithId2 = null, dbWithId3 = null, oldMaster = null; try { proc = run("1"); Thread.sleep(12000); dbWithId2 = startDb(2); dbWithId3 = startDb(3); assertTrue(!dbWithId2.isMaster()); assertTrue(!dbWithId3.isMaster()); final CountDownLatch newMasterAvailableLatch = new CountDownLatch(1); dbWithId2 .getDependencyResolver() .resolveDependency(ClusterClient.class) .addAtomicBroadcastListener( new AtomicBroadcastListener() { @Override public void receive(Payload value) { try { Object event = new AtomicBroadcastSerializer().receive(value); if (event instanceof MemberIsAvailable) { if (HighAvailabilityModeSwitcher.MASTER.equals( ((MemberIsAvailable) event).getRole())) { newMasterAvailableLatch.countDown(); } } } catch (Exception e) { fail(e.toString()); } } }); proc.destroy(); proc = null; newMasterAvailableLatch.await(60, SECONDS); assertTrue(dbWithId2.isMaster()); assertTrue(!dbWithId3.isMaster()); oldMaster = startDb(1); long oldMasterNode = createNamedNode(oldMaster, "Old master"); assertEquals(oldMasterNode, getNamedNode(dbWithId2, "Old master")); } finally { if (proc != null) { proc.destroy(); } if (oldMaster != null) { oldMaster.shutdown(); } dbWithId2.shutdown(); dbWithId3.shutdown(); } }
public void stop() { if (isRunning) { addReport("SfM stopped"); isRunning = false; thread.interrupt(); if (bundlerProcess != null) { bundlerProcess.destroy(); } for (Process process : imageManager.getActiveProcesses()) { process.destroy(); } } }
@Test public void testConnectionListener() throws IOException, InterruptedException, TimeoutException { Process p = runRedis(); final Waiter onConnectWaiter = new Waiter(); final Waiter onDisconnectWaiter = new Waiter(); Config config = new Config(); config.useSingleServer().setAddress("127.0.0.1:6319").setFailedAttempts(1).setRetryAttempts(1); config.setConnectionListener( new ConnectionListener() { @Override public void onDisconnect(InetSocketAddress addr) { onDisconnectWaiter.assertEquals(new InetSocketAddress("127.0.0.1", 6319), addr); onDisconnectWaiter.resume(); } @Override public void onConnect(InetSocketAddress addr) { onConnectWaiter.assertEquals(new InetSocketAddress("127.0.0.1", 6319), addr); onConnectWaiter.resume(); } }); RedissonClient r = Redisson.create(config); r.getBucket("1").get(); p.destroy(); Assert.assertEquals(1, p.waitFor()); try { r.getBucket("1").get(); } catch (Exception e) { } p = runRedis(); r.getBucket("1").get(); r.shutdown(); p.destroy(); Assert.assertEquals(1, p.waitFor()); onConnectWaiter.await(1, TimeUnit.SECONDS, 2); onDisconnectWaiter.await(); }
public void run() { if (this.pid == null) { return; } try { Process process = new ProcessBuilder().command("su").redirectErrorStream(true).start(); InputStream stdout = process.getInputStream(); OutputStream stdin = process.getOutputStream(); SUKillerOutputThread stdoutThread = new SUKillerOutputThread(); stdoutThread.setInputStream(stdout); stdoutThread.start(); String kill = "kill -9 " + this.pid + "\n"; stdin.write(kill.getBytes(), 0, kill.length()); stdin.write("exit\n".getBytes(), 0, "exit\n".length()); stdin.flush(); process.waitFor(); stdoutThread.interrupt(); try { process.destroy(); } catch (Exception e) { } Message msg = Message.obtain(ExecActivity.handler, 3); ExecActivity.handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } }
public static boolean upgradeRootPermission(String pkgCodePath) { Process process = null; DataOutputStream os = null; try { String cmd = "chmod 755 " + pkgCodePath; process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { return false; } finally { try { if (os != null) { os.close(); } assert process != null; process.destroy(); } catch (Exception ignored) { } } return true; }
public void backup() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in backup: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing backup process: " + e.getMessage()); } } log( "build.prop Backup at " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak"); }
public final void shutdown() { // we need to be a little considerate to the output. given // there are all kinds of threads running, we make sure we // wait for all the output to complete. shuttingDown = true; // isolate the process first Process process = null; if (vm != null) process = vm.process(); try { if (vm != null) { vm.dispose(); vm = null; eventHandler.shutdown(); } sioSocket.close(); } catch (Exception ex) { // do nothing } finally { if (process != null) { process.destroy(); // XXX sun's jdb implementation works a lot to make sure // the stderr and stdout are dumped before killing // things. i'm not sure how important it is, or even how // well it works (given i can't test it) // sooo, if the reader finds bugs with the output handling // on finish, lemme know. } jdebug.removeApplication(appID); } }
/** * This method runs the ProcessBuilder and waits for it to finish. At the end it checks the return * state from the process and if it is a failure it prints the last line of the console output. * * @param builder */ private void bashProcess(ProcessBuilder builder) { Process process = null; builder.redirectErrorStream(true); try { process = builder.start(); } catch (IOException e1) { e1.printStackTrace(); } InputStream stdout = process.getInputStream(); BufferedReader stdoutBuffered = new BufferedReader(new InputStreamReader(stdout)); String line = null; String last = null; try { while ((line = stdoutBuffered.readLine()) != null) { last = line; if (isCancelled()) { process.destroy(); return; } } } catch (IOException e1) { e1.printStackTrace(); } try { if (process.waitFor() != 0) { firePropertyChange("failure", null, last); errorState = true; } } catch (InterruptedException e1) { e1.printStackTrace(); } }
@Test public void shouldDumpProcessInformation() throws Exception { // GIVEN // a process spawned from this test which pauses at a specific point of execution Process process = getRuntime() .exec( new String[] { "java", "-cp", getProperty("java.class.path"), DumpableProcess.class.getName(), SIGNAL }); awaitSignal(process); // WHEN // dumping process information for that spawned process (knowing it's in the expected position) Pair<Long, String> pid = single( DumpProcessInformation.getJPids(stringContains(DumpableProcess.class.getSimpleName()))); File threaddumpFile = DumpProcessInformation.doThreadDump(pid, directory); process.destroy(); // THEN // the produced thread dump should contain that expected method at least assertTrue(fileContains(threaddumpFile, "traceableMethod", DumpableProcess.class.getName())); }
public String getLauncherDetails(String prefix) { try { final String javaVersionCommand = javaCommand + " -version"; Process proc = Runtime.getRuntime().exec(javaVersionCommand); try { InputStream inputStream = proc.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(prefix); buffer.append(line); buffer.append('\n'); } return buffer.toString(); } finally { proc.destroy(); } } catch (Exception e) { throw new RuntimeException(e); } }
/* * (non-Javadoc) * * @see se_tpb_speechgen2.tts.concurrent.TTSAdapter#close() */ public void close() throws IOException { mWriter.write("\n"); mWriter.flush(); mWriter.close(); mReader.close(); mProcess.destroy(); /* * mWriter.write(System.getProperty("line.separator")); mWriter.flush(); * mWriter.close(); mReader.close(); * * int exitVal = -1; long pollInterval = 1000; long startTime = * System.currentTimeMillis(); * * do { try { exitVal = mProcess.exitValue(); } catch * (IllegalThreadStateException ignored) { * * try { Thread.sleep(pollInterval); } catch (InterruptedException * ignoredAgain) { / * nothing here, we are just trying to shutdown. * / } } } * while (exitVal < 0 && (mTimeout > (System.currentTimeMillis() - * startTime))); * * if (exitVal < 0) { mProcess.destroy(); } * * if (exitVal != 0) { String msg = "Filibuster error occurred: At least " + * exitVal + " skipped phrase" + (exitVal > 1? "s" : "") + ", please * refer to the filibuster error logs for more information."; throw new * TTSException(msg); } else if (exitVal < 0) { String msg = "Filibuster * returned error: " + exitVal + ", " + "please refer to the filibuster * error logs for more information."; throw new TTSException(msg); } * */ }
public static void executeCommandAndExit(String command) throws IOException, InterruptedException { logger.info("Entering method executeCommand"); Runtime rt = Runtime.getRuntime(); String line = null; logger.info("Command to be executed = " + command); prcs = rt.exec(command); BufferedReader stdError = new BufferedReader(new InputStreamReader(prcs.getErrorStream())); logger.info("ERROR in the process - (if any)"); while ((line = stdError.readLine()) != null) { logger.info(line); } logger.info("End of error"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(prcs.getInputStream())); logger.info("Output of the process - (if any)"); while ((line = stdInput.readLine()) != null) { logger.info(line); } logger.info("End of output"); int exitVal = prcs.waitFor(); logger.info("Process exitValue: " + exitVal); prcs.destroy(); logger.info("Exiting the method"); }
public static void executeInTerminalCommandAndExit(String command) throws IOException, InterruptedException { String line = null; logger.info("Entering method executeCommand"); PrintWriter out = new PrintWriter( new OutputStreamWriter(new BufferedOutputStream(prcs.getOutputStream())), true); logger.info("Command to be executed = " + command); out.println(command); out.println("exit"); BufferedReader stdError = new BufferedReader(new InputStreamReader(prcs.getErrorStream())); logger.info("ERROR in the process - (if any)"); while ((line = stdError.readLine()) != null) { logger.info(line); } logger.info("End of error"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(prcs.getInputStream())); logger.info("Output of the process - (if any)"); while ((line = stdInput.readLine()) != null) { logger.info(line); } logger.info("End of output"); int exitVal = prcs.waitFor(); logger.info("Process exitValue: " + exitVal); prcs.destroy(); }
private boolean pack200(final File sourceFile, final File targetFile) throws IOException { JarFile jarFile = new JarFile(sourceFile); try { if (isSigned(jarFile)) { return false; } try { String pack200Executable = new File(System.getProperty("java.home"), "bin/pack200" + (isWindows() ? ".exe" : "")) .getAbsolutePath(); ProcessBuilder pb = new ProcessBuilder( pack200Executable, targetFile.getAbsolutePath(), sourceFile.getAbsolutePath()); pb.directory(sourceFile.getParentFile()); int result; Process process = pb.start(); result = process.waitFor(); process.destroy(); return result == 0; } catch (InterruptedException e) { return false; } finally { if (targetFile.exists()) { targetFile.setLastModified(sourceFile.lastModified()); } } } finally { jarFile.close(); } }
/* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.interfaces.IDisposable#dispose() */ @Override public void dispose() { if (process != null) { process.destroy(); process = null; } }
private static void fillLogcat(final OutputStream ping) { if (Versions.preJB) { // Logcat retrieval is not supported on pre-JB devices. return; } try { // get the last 200 lines of logcat Process proc = (new ProcessBuilder()) .command("/system/bin/logcat", "-v", "threadtime", "-t", "200", "-d", "*:D") .redirectErrorStream(true) .start(); try { Reader procOut = new InputStreamReader(proc.getInputStream(), TRACES_CHARSET); int size = fillPingBlock(ping, procOut, null); if (DEBUG) { Log.d(LOGTAG, "wrote logcat, size = " + String.valueOf(size)); } } finally { proc.destroy(); } } catch (IOException e) { // ignore because logcat is not essential Log.w(LOGTAG, e); } }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
public static Process launch(String path, boolean detached) throws InterruptedException { Process p = null; if (detached) { File f = new File(path); try { Desktop.getDesktop().open(f); } catch (IOException e) { e.printStackTrace(); } return p; } // else try { p = Runtime.getRuntime().exec(path); new Thread(new ProcessDestroyWatcher(p)).start(); // new Thread(new ProcessHandler(p, ProcessHandler.typeHandler.STANDARD)).start(); // Xming // n'utilise que la sortie d'erreur new Thread(new ProcessHandler(p, ProcessHandler.typeHandler.ERROR)).start(); p.destroy(); } catch (IOException e) { e.printStackTrace(); } return p; }
private Process startProcessAndWait(List<String> commandString, boolean capture) { boolean isWindows = isWindows(); Process p = null; try { ProcessBuilder bp = new ProcessBuilder(commandString); String pname = commandString.get(0); if (isWindows) { pname = pname.substring(pname.lastIndexOf("\\") + 1); } else { pname = pname.substring(pname.lastIndexOf("/") + 1); } p = bp.start(); StreamHog errorHog = new StreamHog(pname, p.getErrorStream(), capture); StreamHog outputHog = new StreamHog(pname, p.getInputStream(), capture); if (!isWindows) { /* * on Windows the process will never return, so we cannot wait */ try { p.waitFor(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } } return p; } catch (IOException ex) { Exceptions.printStackTrace(ex); if (p != null) { Logger.getLogger(RserveConnectionFactory.class.getName()) .info("Trying to destroy process!"); p.destroy(); } } return p; }
/** Runs the process. */ void run() throws Exception { Process process = processBuilder.start(); try { new InputThread(process.getInputStream()).start(); new ErrorThread(process.getErrorStream()).start(); synchronized (this) { while (!done) { long wait = stop - System.currentTimeMillis(); if (wait <= 0) { break; } try { wait(wait); } catch (InterruptedException e) { break; } } } if (exception instanceof Exception) { throw (Exception) exception; } else if (exception instanceof Error) { throw (Error) exception; } else if (exception != null) { throw new Exception("Unexpected exception: " + exception); } else if (!done) { fail("Process timed out"); } } finally { process.destroy(); process.waitFor(); } }
public void startServer() throws Exception { String[] vmArgs = new String[] { "-Dorg.hornetq.logger-delegate-factory-class-name=org.hornetq.jms.SysoutLoggerDelegateFactory" }; serverProcess = SpawnedVMSupport.spawnVM(SpawnedJMSServer.class.getName(), vmArgs, false); InputStreamReader isr = new InputStreamReader(serverProcess.getInputStream()); final BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println("SERVER: " + line); line.replace('|', '\n'); if ("OK".equals(line.trim())) { new Thread() { @Override public void run() { try { String line = null; while ((line = br.readLine()) != null) { System.out.println("SERVER: " + line); } } catch (Exception e) { e.printStackTrace(); } } }.start(); return; } else if ("KO".equals(line.trim())) { // something went wrong with the server, destroy it: serverProcess.destroy(); throw new IllegalStateException("Unable to start the spawned server :" + line); } } }
public void makeTemp() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes( "chmod 777 " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in making temp file: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing temp process: " + e.getMessage()); } } tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp"; }
// ******************** public boolean runRootCommand(String command) { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { Log.d("*** DEBUG ***", "Unexpected error - Here is what I know: " + e.getMessage()); return false; } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { // nothing } } return true; }
public void destroyTCP() throws IOException { running = false; closeFile(); if (process != null) { process.destroy(); } }
private void serve(InputStream sis, OutputStream sos) throws IOException { // kills the process if client closes the stream; // closes the stream if process is terminated/ended output. // therefore we need the interruption mechanism. Process process = Runtime.getRuntime().exec("bash"); InputStream pis = process.getInputStream(); InputStream pes = process.getErrorStream(); OutputStream pos = process.getOutputStream(); try { threads.add(new CopyThread(pis, sos)); threads.add(new CopyThread(pes, sos)); threads.add(new CopyThread(sis, pos)); threads.add( new InterruptibleThread() { protected void run0() throws InterruptedException { process.waitFor(); } }); Util.startJoin(threads); } finally { process.destroy(); } }
/** * 变成一个系统的app * * @param context * @param name */ public static void toSystemApp(Context context, String name) { String packageName = context.getPackageName(); String[] commands = { "busybox mount -o remount,rw /system", "busybox cp /data/data/" + packageName + "/files/" + name + " /system/app/" + name, "busybox rm /data/data/" + packageName + "/files/" + name }; Process process = null; DataOutputStream dataOutputStream = null; try { process = Runtime.getRuntime().exec("su"); dataOutputStream = new DataOutputStream(process.getOutputStream()); int length = commands.length; for (int i = 0; i < length; i++) { dataOutputStream.writeBytes(commands[i] + "\n"); } dataOutputStream.writeBytes("exit\n"); dataOutputStream.flush(); process.waitFor(); } catch (Exception e) { } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } process.destroy(); } catch (Exception e) { } } }