Question

I have an execute(String cmd) in a jsp script that calls the exec method from the Runtime class.

It works when I call a local command, like a php script stored on the server. for example: /usr/bin/php /path/to/php/script arg1 arg2

So I guess my execute command is ok, since it is working with that.

Now when I try to call lynx, the text-based web browser, it does not work.

If I call it in a terminal, it works fine: /usr/bin/lynx -dump -accept_all_cookies 'http://www.someurl.net/?arg1=1&arg2=2'

But when I call this from my execute command, nothing happens...

Any idea why?

This is my execute method:

public String execute(String cmd){


        Runtime r = Runtime.getRuntime();
        Process p = null;
        String res = "";

        try {
                    p = r.exec(cmd);
                    InputStreamReader isr = new InputStreamReader(p.getInputStream());
                    BufferedReader br = new BufferedReader(isr);
                    String line = null;
                    //out.println(res);
                    while ((line = br.readLine()) != null) {

                    res += line;

                    }
                    p.waitFor();
                    } catch (Exception e) {
                    res += e;
                    }
                    System.out.println(p.exitValue());

        return res;

    }
Was it helpful?

Solution 2

I solved it.... by calling lynx into a php script, php script that I called from the Jsp script...

It's a shitty solution but at least it works... I still do not really understand why the exec command from Java works that way...

Thanks for your help anyway Andrzej (Czech I guess from the name..? ^_^), somehow you put me on the way!

OTHER TIPS

You need to read from the Process' output stream.

Since you're not, the underlying lynx process is likely blocking while writing output, waiting for someone to empty the output stream's buffer. Even if you're going to ignore the output, you need to read it anyway for the process to execute as you'd expect.

As the javadocs of Process say, "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock."

See http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html for some examples of how to handle this.

Edit: in case you are wondering, chances are that when you invoked the PHP script it didn't produce a great deal of output, and so was able to terminate before filling the output buffer and blocking. The lynx command is presumably producing more output and hence hitting this issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top