0

我正在尝试使用 commons exec 包为 Java 运行一些 shell 脚本,并使用 PumpStreamHandler 清除 STDOUT 和 STDERR 缓冲区。大多数脚本运行良好,没有任何问题,但其中一些会挂起。

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

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

4

3 回答 3

0

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

你会发现各种各样的事情正在发生。脚本停止并提示输入(挂断的大来源)错误解析不正确,段错误,文件未找到。

于 2011-05-19T18:39:02.370 回答
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();
于 2011-07-26T09:22:19.833 回答
0

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

#!/bin/bash

sleep 60;
echo "if  you are patient, here is your response"
于 2011-05-19T21:06:09.507 回答