从Java运行shell脚本

时间:2011-05-19 18:15:07

标签: java shell exec apache-commons-exec

我正在尝试使用commons exec包运行一些Java脚本,并清除STDOUT& STDERR使用PumpStreamHandler缓冲。大多数脚本运行正常没有任何问题,但其中一些是挂起的。

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

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

3 个答案:

答案 0 :(得分:0)

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

你会发现各种各样的事情。停止并提示输入(挂起的大来源)错误的脚本,这些错误无法正确解析,seg错误,找不到文件。

答案 1 :(得分:0)

要扩展关于直接运行命令以进行测试的第一个答案,您可以使用一个简单的脚本来测试您的假设,该脚本在返回输出之前会休眠一段时间。如果你 无法测试你的命令,测试你的想法。

#!/bin/bash

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

答案 2 :(得分: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();