Solved

Execute shell script from java

Posted on 2004-04-19
6
3,401 Views
Last Modified: 2013-11-24
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());
    }
0
Comment
Question by:javagirip
  • 3
  • 2
6 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 125 total points
ID: 10858726
Try running it with this class:



public class CommandRunner {

      private int returnValue = Integer.MIN_VALUE;



      public int getReturnValue() {
            return returnValue;
      }



      public static void main(String[] args) {
            new CommandRunner().run(args);
      }






      public void run(String[] args) {

            try {

                  if (args.length < 1) {
                        System.out.println("Usage: java CommandRunner <command string>");
                        System.exit(-1);
                  }
                  Process pro = null;
                  if (args.length > 1) {
                        pro = Runtime.getRuntime().exec(args);
                  }
                  else {
                        pro = Runtime.getRuntime().exec(args[0]);
                  }
                  InputStream error = pro.getErrorStream();
                  InputStream output = pro.getInputStream();
                  Thread err = new Thread(new OutErrReader(error));
                  Thread out = new Thread(new OutErrReader(output));
                  out.start();
                  err.start();
                  returnValue = pro.waitFor();
            }
            catch (java.io.IOException e) {
                  e.printStackTrace();
            }
            catch (java.lang.InterruptedException e) {
                  e.printStackTrace();
            }

      }


      class OutErrReader implements Runnable {
            InputStream is;


            public OutErrReader(InputStream is) {
                  this.is = is;
            }


            public void run() {
                  try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(is));
                        String temp = null;
                        while ((temp = in.readLine()) != null) {
                              System.out.println(temp);
                        }
                        is.close();
                  }
                  catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }
}
0
 

Author Comment

by:javagirip
ID: 10858907
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));

0
 

Author Comment

by:javagirip
ID: 10858921
Oops, I forgot to copy the inner class file, let me try now
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 4

Expert Comment

by:john-at-7fff
ID: 10859067
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

0
 

Author Comment

by:javagirip
ID: 10859895
IT worked.

Thanks a lot!!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10860236
8-)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now