java中创建进程

Java中提供了两种方法来启动其它进程:
方法一:
	Process process = new ProcessBuilder(cmd).start();
方法二:
	Process process = Runtime.getRuntime().exec(cmd);
	注意:底层也是调用方法一。


Process的waitFor()方法:
	说明:等待Process结束后返回Process的返回值,若Process一直未结束,则程序一直等待下去。
	分析:
		创建的新进程与jvm建立三个管道连接:标准输入流、标准输出流、标准错误输出流。
		若新进程不断向标准输入流、标准错误输出流写数据,而jvm不读取的话,则会导致缓冲区塞满而无法继续写数据,从而造成新进程一直不结束,最终导致调用waitFor()方法的线程阻塞。
	解决:
		jvm读取新进程写入缓存区的数据(即:标准输入流Process.getInputStream()、标准错误输出流Process.getErrorStream()中的数据)即可。
		eg:
			    // 打印进程的输出信息
	            List<String> outputStr = IOUtils.readLines(process.getInputStream(), "UTF-8");
	            List<String> errorOutputStr = IOUtils.readLines(process.getErrorStream(), "UTF-8");
	            LOGGER.info("=============new process output start =======");
	            LOGGER.info(outputStr.toString());
	            LOGGER.info("=============new process output end =======");
	            LOGGER.info("=============new process error output start =======");
	            LOGGER.info(errorOutputStr.toString());
	            LOGGER.info("=============new process error output end =======");

	相关源码:
	    /**
	     * Causes the current thread to wait, if necessary, until the process represented by this {@code Process} object has terminated.  
	     * This method returns immediately if the subprocess has already terminated.  
	     * If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
	     */
	    public synchronized int waitFor() throws InterruptedException {
	        while (!hasExited) {
	            wait();
	        }
	        return exitcode;
	    }


	    /**
	     * Returns the input stream connected to the normal output of the subprocess.  
	     * The stream obtains data piped from the standard output of the process represented by this {@code Process} object.
	     */
	    public abstract InputStream getInputStream();


	    /**
	     * Returns the input stream connected to the error output of the subprocess. 
	     * The stream obtains data piped from the error output of the process represented by this {@code Process} object.
	     */
	    public abstract InputStream getErrorStream();


	    /**
	     * Returns the output stream connected to the normal input of the subprocess.  
	     * Output to the stream is piped into the standard input of the process represented by this {@code Process} object.
	     */
	    public abstract OutputStream getOutputStream();




	    


 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值