类java.lang.Process源码实例Demo

下面列出了怎么用java.lang.Process的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: ShareBox   文件: WifiUtil.java
public static ArrayList<String> nativeGetConnectedIP(String deviceName) {
        ArrayList<String> connectedIP = new ArrayList<String>();
        try {
            Process local=Runtime.getRuntime().exec("cat /proc/net/arp");

            DataInputStream os=new DataInputStream(local.getInputStream());

            String line;
            Log.i(TAG,"arp begin");
            while ((line = os.readLine()) != null) {
                Log.i(TAG, line);
                String[] splited = line.split("\\s+");
                if (splited != null && splited.length > 5) {
                    if(!splited[3].equals("00:00:00:00:00:00")&&splited[5].contains(deviceName)){
                        String ip = splited[0];
                        connectedIP.add(ip);
                    }
                }
            }
            Log.i(TAG,"arp end");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        connectedIP.remove(0);
        return connectedIP;
    }
 
源代码2 项目: spring-rest   文件: EnvInfo.java
final

  public static Map<String,String> mapEnvInfo(String filter) throws IOException {
      Process proc = Runtime.getRuntime().exec("env");
      Map<String, String> ret = new HashMap<>();
            try (InputStream stream = proc.getInputStream()) {
          try (Scanner s = new Scanner(stream).useDelimiter("\\n")) {
        	  while (s.hasNext())
        	  {
                  String val =  s.next();
                  String[] nameVal = val.split("=");
                  if (filter.equalsIgnoreCase("*"))
                	  ret.put(nameVal[0],nameVal.length > 1 ? nameVal[1] : "");
                  else
                  {
                	  if (nameVal[0].startsWith(filter))
                	  {
                    	  ret.put(nameVal[0],nameVal.length > 1 ? nameVal[1] : "");
                	  }
                  }
                  
        	  }
          } 
      } 
      return ret;
  }
 
源代码3 项目: dacapobench   文件: DaCapoClientRunner.java
public static void initialize(String carName, String size, int numThreads, boolean useBeans) {
  try {

    car = carName;

    /* Calling this function directly does not launch the client now. According to testing, it seems the getMain method of boot does not work properlly.
       Thus these ugly codes are temporarily used fot verifing that the whole framework works
       Will be changed once the problem is fixed
    */
    //ClientCLI.main(new String[] { car, "-i", "-t", numThreads + "", "-s", size, useBeans ? "-b" : "" });


    gero = System.getProperty("org.apache.geronimo.home.dir");
    String jhome= System.getProperty("java.home");
    ProcessBuilder pb = new ProcessBuilder(jhome + "/bin/java", "-jar", "-Dkaraf.startLocalConsole=false",gero + "/bin/client.jar", car, "-i", "-t", numThreads + "", "-s", size, useBeans ? "-b" : "");
    Process p = pb.start();
    p.waitFor();

  } catch (Exception e) {
    System.err.print("Exception initializing client: " + e.toString());
    e.printStackTrace();
    System.exit(-1);
  }
}
 
源代码4 项目: jdk9-jigsaw   文件: ProcessManager.java
public List<String> allProcesses() {
	List<String> processes = new LinkedList<String>();
	try {
	    String line;
	    Process p = null;
	    if(System.getProperty("os.name").toLowerCase().contains("win")) {
		    p = Runtime.getRuntime().exec
		    	    (System.getenv("windir") +"\\system32\\"+"tasklist.exe");
	    } else {
		    p = Runtime.getRuntime().exec("ps -e");
	    }
	    BufferedReader input =
	            new BufferedReader(new InputStreamReader(p.getInputStream()));
	    while ((line = input.readLine()) != null) {
	    	processes.add(line);
	    }
	    input.close();
	} catch (Exception err) {
	    err.printStackTrace();
	}
	
	return processes;
}
 
源代码5 项目: dragonwell8_jdk   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
源代码6 项目: TencentKona-8   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
源代码7 项目: openjdk-jdk8u   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
/**
 * 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;
    }

 }
 
源代码9 项目: openjdk-jdk9   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
源代码10 项目: spring-rest   文件: HostInfo.java
public static String execReadToString(String execCommand) throws IOException {
    Process proc = Runtime.getRuntime().exec(execCommand);
    try (InputStream stream = proc.getInputStream()) {
        try (Scanner s = new Scanner(stream).useDelimiter("\\A")) {
            return s.hasNext() ? s.next() : "";
        }
    }
}
 
源代码11 项目: dacapobench   文件: DaCapoClientRunner.java
public static void runIteration(String size, int numThreads, boolean useBeans) {

    try {

      /* Calling the function directly does not launch the client now. According to testing, it seems the getMain method of boot does not work properlly.
         Thus these ugly codes are temporarily used for checking the whole framework
         Will be changed once the problem is fixed
      */
      //ClientCLI.main(new String[] { car, "-i", "-t", numThreads + "", "-s", size, useBeans ? "-b" : "" });

      String jhome= System.getProperty("java.home");

      ProcessBuilder pb = new ProcessBuilder(jhome + "/bin/java", "-jar", "-Dkaraf.startLocalConsole=false", gero + "/bin/client.jar", car, "-t", numThreads + "", "-s", size, useBeans ? "-b" : "");
      Process p = pb.start();
      p.waitFor();

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while (stdInput.ready()) { //While there's something in the buffer
        //read&print - replace with a buffered read (into an array) if the output doesn't contain CR/LF
        System.out.println(stdInput.readLine());
      }

    } catch (Exception e) {
      System.err.print("Exception running client iteration: " + e.toString());
      e.printStackTrace();
    }
  }
 
源代码12 项目: jdk8u-jdk   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
源代码13 项目: gemfirexd-oss   文件: derbyrunjartest.java
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;
        }
    }
}
 
源代码14 项目: repairnator   文件: RepairnatorPostBuild.java
public void runRepairnator(EnvVars env) throws IOException,InterruptedException{
    Config config = this.config;
    System.out.println("jar location " + config.getJarLocation());
    RepairnatorProcessBuilder repProcBuilder = new RepairnatorProcessBuilder()
                                    .useJavaExec(config.getJavaExec())
                                    .atJarLocation(config.getJarLocation())
                                    .onGitUrl(config.getGitUrl())
                                    .onGitBranch(config.getGitBranch())
                                    .onGitOAuth(config.getGitOAuth())
                                    .withSmtpUsername(config.getSmtpUsername())
                                    .withSmtpPassword(config.getSmtpPassword())
                                    .withSmtpServer(config.getSmtpServer())
                                    .withSmtpPort(config.getSmtpPort())
                                    .shouldNotifyTo(config.getNotifyTo())
                                    .withRepairTools(config.getTools())
                                    .withSonarRules(config.getSonarRules())
                                    .useSmtpTls(config.useTLSOrSSL())
                                    .asNoTravisRepair()
                                    .alsoCreatePR()
                                    .withMavenHome(config.getMavenHome())
                                    .atWorkSpace(config.getTempDir().getAbsolutePath())
                                    .withOutputDir(config.getTempDir().getAbsolutePath());

    ProcessBuilder builder = repProcBuilder.build().directory(config.getTempDir());
    builder.redirectErrorStream(true);
    builder.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE);
    Process process = builder.start();
    this.printProcessOutPut(process);
    process.waitFor();
}
 
源代码15 项目: jdk8u_jdk   文件: MXBeanWeirdParamTest.java
/**
 * 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;
    }

 }
 
源代码16 项目: gemfirexd-oss   文件: derbyrunjartest.java
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;
        }
    }
}
 
源代码17 项目: semanticvectors   文件: MyTestUtils.java
/**
 * 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;
}
 
源代码18 项目: semanticvectors   文件: MyTestUtils.java
/**
 * Spawn a child to execute the main method in Class childMain
 * using the same args and environment as the current runtime.
 * This method prevents a child processes from hanging
 * when its output buffers saturate by creating threads to
 * empty the output buffers.
 * @return The process, already started. Consider using waitForAndDestroy() to clean up afterwards.
 * @param childMain The Class to spawn, must contain main function
 * @param inputArgs arguments for the main class. Use null to pass no arguments.
 * @param in The child process will read input from this stream. Use null to avoid reading input. Always close() your stream when you are done or you may deadlock.
 * @param out The child process will write output to this stream. Use null to avoid writing output.
 * @param err The child process will write errors to this stream. Use null to avoid writing output.
 */
public static Process spawnChildProcess(
    Class<?> childMain, String[] inputArgs, InputStream in, OutputStream out, OutputStream err)
    throws IOException {
  //get the same arguments as used to start this JRE
  RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
  List<String> arglist = rmxb.getInputArguments();
  String cp = rmxb.getClassPath();

  //construct "java <arguments> <main-class-name>"
  ArrayList<String> arguments = new ArrayList<String>(arglist);
  arguments.add(0, "java");
  arguments.add("-classpath");
  arguments.add(cp);
  arguments.add(childMain.getCanonicalName());
  for (String arg : inputArgs) arguments.add(arg);

  //using ProcessBuilder initializes the child process with parent's env.
  ProcessBuilder pb = new ProcessBuilder(arguments);

  //redirecting STDERR to STDOUT needs to be done before starting
  if (err == out) {
    pb.redirectErrorStream(true);
  }

  Process proc;
  proc = pb.start(); //Might throw an IOException to calling method

  //setup stdin
  if (in != null) {
    new OutputReader(in, proc.getOutputStream()).start();
  }

  //setup stdout
  if (out == null) {
    out = new NullOutputStream();
  }
  new OutputReader(proc.getInputStream(), out).start();

  //setup stderr
  if (!pb.redirectErrorStream()) {
    if (err == null) {
      err = new NullOutputStream();
    }
    new OutputReader(proc.getErrorStream(), err).start();
  }

  return proc;
}
 
源代码19 项目: dragonwell8_jdk   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码20 项目: TencentKona-8   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码21 项目: jdk8u60   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码22 项目: openjdk-jdk8u   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码23 项目: openjdk-jdk8u-backup   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码24 项目: openjdk-jdk9   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码25 项目: jdk8u-jdk   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码26 项目: hottub   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码27 项目: openjdk-8-source   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码28 项目: repairnator   文件: RepairnatorPostBuild.java
public void printProcessOutPut(Process process) throws IOException{
    try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(process.getInputStream()))) {
        reader.lines().forEach(line -> System.out.println(line));
    }
}
 
源代码29 项目: openjdk-8   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
源代码30 项目: jdk8u_jdk   文件: Activation.java
void shutdownFast() {
    Process p = child;
    if (p != null) {
        p.destroy();
    }
}
 
 类所在包
 同包方法