2011-05-19 214 views
0

我想通过使用commons exec包运行一些Java脚本,并使用PumpStreamHandler清除STDOUT & STDERR缓冲区。大多数脚本运行正常,没有任何问题,但其中一些挂起。从Java运行shell脚本

特别是那些需要一段时间才能返回的脚本。我的猜测是,PumpStramHandle可能正在读取流结束,因为暂时没有任何东西放在流上,然后缓冲区填满。

有没有更好的方法来解决这个问题?

回答

0

不是最好的解决方案。但是做我需要的。 :)

class OSCommandLogger extends Thread { 
    private static final Logger logger = Logger.getLogger(OSCommandLogger.class); 
    private volatile boolean done = false; 
    private final String name; 
    // Each process is associated with an error and output stream 
    private final BufferedReader outputReader; 
    private final BufferedReader errorReader; 
    private final Logger log; 

    /** 
    * Reads the output & error streams of the processes and writes them to 
    * specified log 
    * 
    * @param p 
    * @param name 
    * @param log 
    */ 
    OSCommandLogger(Process p, String name, Logger log) { 
     // Create readers 
     outputReader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream())); 
     this.log = log; 
     if (name != null) 
      this.name = name; 
     else 
      this.name = "OSCommandStreamsLogger"; 
    } 

    private void logLine(BufferedReader reader, boolean isError) { 
     try { 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       if (log != null && log.isDebugEnabled()) { 
        if (!isError) 
         log.debug("[OuputStream] " + line); 
        else 
         log.warn("[ErrorStream] " + line); 
       } else 
        logger.debug(line); 
      } 
     } catch (Exception ex) { 
      if (log != null) 
       log.error(name + ":" + "Error while reading command process stream", ex); 
     } 
    } 

    public void run() { 
     while (!done) { 
      logLine(outputReader, false); 
      logLine(errorReader, true); 

      try { 
       // Sleep for a while before reading the next lines 
       Thread.sleep(100); 
      } catch (InterruptedException e) { 
       log.debug("Done with command"); 
      } 
     } 

     // Process is done. Close all the streams 
     try { 
      logLine(outputReader, false); 
      outputReader.close(); 

      logLine(errorReader, true); 
      errorReader.close(); 
      if (log != null && log.isDebugEnabled()) 
       log.debug(name + ": Closed output/ error Streams."); 

     } catch (IOException ie) { 
      if (log != null) 
       log.error(name + ":" + "Error while reading command process stream", ie); 
     } 
    } 

    public void stopLoggers() { 
     if (log != null && log.isDebugEnabled()) 
      log.debug(name + ":Stop loggers"); 
     this.done = true; 
    } 
} 

用法:

Process p = Runtime.getRuntime().exec("Command"); 
OSCommandLogger logger = new OSCommandLogger(p, "Command", log); 

// Start the thread using thread pool 
threadExec.executeRunnable(logger); 
int exitValue = p.waitFor(); // Wait till the process is finished 

// Required to stop the logger threads 
logger.stopLoggers(); 
logger.interrupt(); 
0

提取正在执行的脚本/命令,并自己在shell中运行它。当通过其他语言(c,C++,python java等)运行'exec'的东西时,事情开始发生'错误',这应该是第一步。

你会发现各种各样的事情正在进行。脚本停止并提示输入(hangup的大来源)错误,不能正确解析,seg故障,找不到文件。

+0

我承认你是对的。但在这种情况下,这确实不是一种选择。 – 2011-05-19 19:23:41

0

为了扩展第一个直接运行命令来测试的答案,你可以用一个简单的脚本来测试你的假设,该脚本在返回输出之前会休眠一段时间。如果你 不能测试你的命令,请测试你的想法。

#!/bin/bash 

sleep 60; 
echo "if you are patient, here is your response"