简体   繁体   English

Process.getErrorStream不会捕获所有错误

[英]Process.getErrorStream doesn't capture all errors

I use ProcessBuilder to create a Process that runs a script on Linux. 我使用ProcessBuilder创建在Linux上运行脚本的进程。 I need to check if there were errors while executing this script. 我需要在执行此脚本时检查是否有错误。

public static String contentInStream(InputStream stream) throws IOException
{
    return contentInReader(new InputStreamReader(stream));
}

public static String contentInReader(Reader reader) throws IOException
{
    BufferedReader br = new BufferedReader(reader);
    String line;
    String content = "";
    while ((line = br.readLine())!=null)
    {
        content += line+"\n";
    }
    return content;
}

public static void execScript(String script)
{
    ProcessBuilder pb = new ProcessBuilder("sh", script);
    Process process = pb.start();
    process.waitFor();
    String errors = contentInStream(process.getErrorStream());
    if (!errors.isEmpty())
    {
        throw new RuntimeException(errors);
    }
}

In a test script I produce two errors, one by explicitly writing to the error channel, and one by trying to write to a file where the script doesn't have write rights. 在测试脚本中,我产生两个错误,一个错误是通过显式写入错误通道,另一个错误是试图写入该脚本没有写权限的文件。

echo Warning
date > in
>&2 echo Error

The problem is that the string errors only contains "Error", not the error from the command "date > in". 问题是字符串错误仅包含“错误”,而不包含命令“ date> in”中的错误。 The file "in" is not created, as expected. 没有按预期方式创建文件“ in”。 If I try "./testScript.sh > /tmp/std 2> /tmp/err", both errors are in /tmp/err, as expected. 如果我尝试“ ./testScript.sh> / tmp / std 2> / tmp / err”,则两个错误都在/ tmp / err中,如预期的那样。

String errors contains: Error 字符串错误包含: Error

Output when script is run by itself: 脚本本身运行时的输出:
/apps/testScript.sh: line 2: in: Permission denied Error

PS: I also tested with the order of the two last lines in the test script reversed. PS:我还测试了测试脚本中倒数第二行的顺序。 I got the same result, so the error is probably not in contentInReader. 我得到了相同的结果,因此错误可能不在contentInReader中。

I solved it. 我解决了 Apparently the script was executing in a different directory when it was started from the Java process, where the script has write permissions. 显然,从Java进程启动脚本时,脚本在另一个目录中执行,该脚本具有写权限。 So there was no error, and getErrorStream did capture all error output, in this case just "Error". 因此没有错误,并且getErrorStream确实捕获了所有错误输出,在本例中为“ Error”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM