问题描述:我们有个功能需要通过java调用shell脚本进行建表。其中调用进程有两个方法,
1.Process类,Process ps = Runtime.getRuntime().exec(命令);
2.ProcessBuilder:
ProcessBuilder hiveProcessBuilder = new ProcessBuilder(command);
hiveProcessBuilder.start();
这两个都能用,其中我使用的是后面一个,但是存在一个问题,方法调用起来后,并不能直接生成脚本,后来发现只要重启服务,表就建好了,分析发现应该是调起的这个进程阻塞了,然后按照这个思路发现网上有人说法非常可能,应该是进程自己去处理stdout和stderr的输出,就是说,执行的结果不知道是现有错误输出(stderr),还是现有标准输出(stdout)。你无法判断到底那个先输出,所以可能无法读取输出,而一直阻塞。 例如:你先处理标准输出(stdout),但是处理的结果是先有错误输出(stderr),一直在等错误输出(stderr)被取走了,才到标准输出(stdout),这样就产生了阻塞。
解决办法:
- mport java.util.*;
- import java.io.*;
- class StreamGobbler extends Thread
- {
- InputStream is;
- String type;
- StreamGobbler(InputStream is, String type)
- {
- this.is = is;
- this.type = type;
- }
- public void run()
- {
- try
- {
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- String line=null;
- while ( (line = br.readLine()) != null)
- System.out.println(type + ">" + line);
- } catch (IOException ioe)
- {
- ioe.printStackTrace();
- }
- }
- }
- public class ExecRunner
- {
- public static void main(String args[])
- {
- if (args.length < 1)
- {
- System.out.println("USAGE: java GoodWindowsExec <cmd>");
- System.exit(1);
- }
- try
- {
- String osName = System.getProperty("os.name" );
- String[] cmd = new String[3];
- if( osName.equals( "Windows NT" ) )
- {
- cmd[0] = "cmd.exe" ;
- cmd[1] = "/C" ;
- cmd[2] = args[0];
- }
- else if( osName.equals( "Windows 95" ) )
- {
- cmd[0] = "command.com" ;
- cmd[1] = "/C" ;
- cmd[2] = args[0];
- } else {
- StringTokenizer st = new StringTokenizer(command, " ");
- cmd = new String[st.countTokens()];
- int token = 0;
- while (st.hasMoreTokens()) {
- String tokenString = st.nextToken();
- // System.out.println(tokenString);
- cmd[token++] = tokenString;
- }
- }
- Runtime rt = Runtime.getRuntime();
- System.out.println("Execing " + cmd[0] + " " + cmd[1]
- + " " + cmd[2]);
- Process proc = rt.exec(cmd);
- // any error message?
- StreamGobbler errorGobbler = new
- StreamGobbler(proc.getErrorStream(), "ERROR");
- // any output?
- StreamGobbler outputGobbler = new
- StreamGobbler(proc.getInputStream(), "OUTPUT");
- // kick them off
- errorGobbler.start();
- outputGobbler.start();
- // any error???
- int exitVal = proc.waitFor();
- System.out.println("ExitValue: " + exitVal);
- } catch (Throwable t)
- {
- t.printStackTrace();
- }
- }
- }
阻塞方法引用地址:https://tivan.iteye.com/blog/1045518