Link to home
Start Free TrialLog in
Avatar of javagirip
javagirip

asked on

Execute shell script from java

Hi I need to exectue a one line unix (solaris) shell script from my java servlet. I tried using the following code, but got a "broken pipe" IOException. Any idea? Thanks in advance

 try
    {
      Runtime rt = Runtime.getRuntime();
      Process child = rt.exec("rsh -l pgg mymachine \"/usr/local/test_ServerClient 2 10001 \"");
   
      BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));
      outCommand.write("MyShellScript");
      child.waitFor();
      int retCode = child.exitValue();
      outCommand.flush();
     }
    catch(InterruptedException ine)
    {
      System.out.println(ine.getMessage());
    }
    catch(IOException ie)
    {
      System.out.println(ie.getMessage());
    }
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of javagirip
javagirip

ASKER

I tried your code, but getting the following exception

java.lang.NoClassDefFoundError: adb/CommandRunner$OutErrReader

at the following line of the code

Thread err = new Thread(new OutErrReader(error));

Oops, I forgot to copy the inner class file, let me try now
If CEHJ's suggestions doesn't work, note that Runtime.exec() runs differently on different systems. On Solaris and AIX, you usually have to use the alternative method form, where you pass in an array:

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String[],%20java.lang.String[],%20java.io.File)

(If that URL doesn't work in your browser, go to http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html and skip down to the version of exec with the signature: exec(String[] cmdarray, String[] envp)

Here's a discussion:

http://forum.java.sun.com/thread.jsp?thread=57009&forum=31&message=144444

IT worked.

Thanks a lot!!
8-)