Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in collecting output of executing external command in Groovy

Following code gets stuck(which I think is blocking I/O) many times (works some time).

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. I am not able to understand why does the 1st way i.e taking input by proc.in.text hangs some time? Does not look 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 2nd approach. Although it works good I wish I could know whats wrong with 1st approach ? Has anyone has encountered this scenario before?

like image 846
Aniket Thakur Avatar asked Aug 14 '14 05:08

Aniket Thakur


1 Answers

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.

like image 163
tim_yates Avatar answered Oct 26 '22 19:10

tim_yates