Aniket Thakur
Aniket Thakur

Reputation: 68935

Difference in collecting output of executing external command in Groovy

The following code gets stuck (which I think is blocking I/O) many times (it works sometimes).

def static executeCurlCommand(URL){
    def url = "curl " + URL;
    def proc = url.execute();
    def output = proc.in.text;
    return output;
}

But when I changes the code to

def static executeCurlCommand(URL){
    def url = "curl " + URL;
    def proc = url.execute();
    def outputStream = new StringBuffer();
    proc.waitForProcessOutput(outputStream, System.err)
    return outputStream.toString();
}

it works fine every time. Why does the first way, i.e., taking input by proc.in.text hang some time? It does not look like an environment-specific problem as I tried it on Windows as well as Cygwin.

To test/run the above method I have tried -

public static void main(def args){
    def url = 'http://mail.google.com';
    println("Output: " + executeCurlCommand(url));
}

I have seen multiple questions on SO and all provide the second approach. Although it works good, I wish I could know what’s wrong with the first approach.

Upvotes: 7

Views: 2756

Answers (1)

tim_yates
tim_yates

Reputation: 171084

The first approach fills a buffer up and then blocks waiting for more room to write output to.

The second approach streams output from the buffer via a separate thread as the process is running, so the process doesn't block.

Upvotes: 7

Related Questions