7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289

1 Answers1

7

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.

tim_yates
  • 167,322
  • 27
  • 342
  • 338