Feedback from runtime.exec(command)

Hi,
I hope someone can point out the problem with the following. I have a method that is supposed to execute a shell command. The shell command would look something like the following:
serctl add 351 password [email protected]
However when this command is executed in a shell/command line a prompt is shown ("MySql password:")asking for a password. Once the user enters the password, the user is added. My code currently executes the first half of the command but gets stuck on the password prompt. My code stops by the line "before the loop" and never enters the inner loop. So obviously my code isn't working properly to say that if the response is a password prompt, to pass it the password variable.
Any ideas?
Many Thanks.
void addUser(String username, String password, String email, String passwd, HttpServletResponse response) throws IOException {
   String[] command = {"serctl", "add", username, password, email};
   //String[] command = {"pstree"};
   Runtime runtime = Runtime.getRuntime();
   Process process = null;
   response.setContentType(CONTENT_TYPE);
   PrintWriter out = response.getWriter();
   String s = "something";
   try {
     process = runtime.exec(command);
     System.out.println("Process is: " + process);
     System.out.println("Command is: " + command);
     BufferedReader in =
     new BufferedReader(new InputStreamReader(process.getInputStream()));
     BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
     OutputStream stdout = process.getOutputStream();
     System.out.println("before the loop");
     s=in.readLine();
     System.out.println(s);
     System.out.println(s);
     System.out.println(in);
     System.out.println(stdout);
     //while((s=in.readLine())!= null)
     while((s=in.readLine()).equals("MySql password: "))
       //s = in.readLine();
       System.out.println(in.readLine());
       System.out.println(s);
       out.println(s);
       if (s.equals("MySql password:  ")) {
         System.out.println("Must be equal to MySql password;");
         //stdout.write(passwd.getBytes());
         //stdout.write(adminpassword);
         //stdout.flush();
         //break;
    System.out.println("after the loop");
     System.out.println("Here is the standard error of the command(if any):\n");
     while ((s = error.readLine()) != null){
       System.out.println(s);
     stdout.close();
     in.close();
     error.close();
     out.println(in);
     out.println("<html>");
     out.println("<body bgcolor=\"#FFFCCC\">");
     out.println("You have successfully added a new user.<br><br>");
     out.println("User " + username + " has been created ");
     out.println("</body></html>");
    catch (Exception e) {
          System.out.println("Uh oh! Error adding new user.");
          e.printStackTrace();
}

Just a random observation:
Sometimes programs that prompt for passwords do it in a way that is impossible to redirect (or at least requires special trickery, such as creating a pseudo-TTY). E.g. in Unix this involves opening /dev/tty and using that instead of stdout & stdin. This is done to make sure there really is a person who knows the password sitting there in front of the teletype.
I don't know if the "serctl" program does that. If stdout&stdin redirection does not appear to work then it is a possibility.
A quick googling for "serctl" reveals:
Commands labeled with (*) will prompt for a MySQL password.
If the variable PW is set, the password will not be prompted.
which might or might not be an easier way to deal with this particular program. If it indeed is the same "serctl" program.

Similar Messages

  • How can I run Runtime.exec command in Java To invoke several other javas?

    Dear Friends:
    I met a problem when I want to use a Java program to run other java processes by Runtime.exec command,
    How can I run Runtime.exec command in Java To invoke several other java processes??
    see code below,
    I want to use HelloHappyCall to call both HappyHoliday.java and HellowWorld.java,
    [1]. main program,
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloHappyCall
         public static void main(String[] args){
              try
                   Runtime.getRuntime().exec("java  -version");
                   Runtime.getRuntime().exec("cmd /c java  HelloWorld "); // here start will create a new process..
                   System.out.println("Never mind abt the bach file execution...");
              catch(Exception ex)
                   System.out.println("Exception occured: " + ex);
    } [2]. sub 1 program
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloWorld
         public static void main(String[] args){
         System.out.println("Hellow World");
    } [3]. Sub 2 program:
    package abc;
    import java.util.*;
    import java.io.*;
    class HappyHoliday
         public static void main(String[] args){
         System.out.println("Happy Holiday!!");
    } When I run, I got following:
    Never mind abt the bach file execution...
    I cannot see both Java version and Hellow World print, what is wrong??
    I use eclipse3.2
    Thanks a lot..

    sunnymanman wrote:
    Thanks,
    But How can I see both programs printout
    "Happy Holiday"
    and
    "Hello World"
    ??First of all, you're not even calling the Happy Holiday one. If you want it to do something, you have to invoke it.
    And by the way, in your comments, you mention that in one case, a new process is created. Actually, new processes are created each time you call Runtime.exec.
    Anyway, if you want the output from the processes, you read it using getInputStream from the Process class. In fact, you really should read that stream anyway (read that URL I sent you to find out why).
    If you want to print that output to the screen, then do so as you'd print anything to the screen.
    in notepad HelloWorld.java, I can see it is opened,
    but in Java, not.I have no idea what you're saying here. It's not relevant whether a source code file is opened in Notepad, when running a program.

  • Reading InputStream from Runtime.exec() and ffmpeg?

    I've got a lot of things going on here and I'm having trouble debugging. I'm working on a streaming music player, and the platform only handles MP3 natively. Specifically, the method that handles incoming requests has to return an InputStream for further processing upstream (out of my visibility).
    I'm trying to extend the music player to play AAC files with the extension ".m4a". To do this, my plan is to transcode from MP3 to AAC using Runtime.exec() and ffmpeg, and then return an InputStream that contains the MP3. This works fine if I use ffmpeg to transcode to a temp file, and then return a FileInputStream constructed from that temp file. But like I said, this is supposed to be a steaming music player, and the blocking for the ~30 seconds it takes to completely transcode to a file is too much of a delay.
    So what I'm trying to do is have ffmpeg transcode to stdout, and then use Process.getInputStream() to return the InputStream that contains ffmpeg's stdout while the transcoding is still going on. This doesn't work and I'm not sure why. (I'm fairly new to java, and this is the first time I've used Runtime.) My player just hangs there. I know Runtime is picky about exhausting the stdout and stderr streams, so I'm not sure if it's something related to that, or if I somehow need to buffer the stdout before returning it, or if I need to run something in a different thread, or if I'm just completely barking up the wrong tree.
    If anyone has any experience with something like this, or can point me at some code that implements something similar, I'd appreciate the help.
    Below a sample of the code in question. Also, for what it's worth, all of the console messages that I put in there are printing, but the music doesn't play.
       public InputStream getStream(String uri) throws IOException
                 System.out.println("Entering Factory.getStream()");
                  System.out.flush();
                File file = new File(URLDecoder.decode(uri, "UTF-8"));
                if (file.exists())
                     if(file.getPath().toLowerCase().endsWith(".mp3")) {
                            // This code for playing MP3 files works correctly
                          System.out.println("Playing MP3");
                          System.out.flush();
                          InputStream in = new FileInputStream(file);
                          return in;
                     else if(file.getPath().toLowerCase().endsWith(".m4a")){
                          System.out.println("Playing M4A");
                          System.out.flush();
                          // Create array for ffmpeg command line
                            // This command line transcodes to STDOUT
                          String[] command = { this.ffmpeg_path,
                                                             "-i", 
                                                             "input.m4a",
                                                             "-acodec",
                                                             "libmp3lame",
                                                             "-ac",
                                                             "2",
                                                             "-ab",
                                                             "256",
                                                             "-f",
                                                             "mp3",
                          // Begin transcoding with ffmpeg
                          System.out.println("Transcoding...");
                          System.out.flush();
                          Runtime runtime = Runtime.getRuntime();
                          Process ffmpeg = runtime.exec(command);
                          // Must exhaust error stream, or the application can become deadlocked.
                          System.out.println("Exhausting stderr...");
                          System.out.flush();
                          this.exhaustInputStream(ffmpeg.getErrorStream());
                          // Return ffmpeg's stdout as an input stream
                          System.out.println("Returning stdout...");
                          System.out.flush();
                          return ffmpeg.getInputStream();
                     else {
                          System.out.println("Unsupported Audio File");
                          System.out.flush();
                          return null;
                else
                    // We aren't requesting a file, so let the API handle the request upstream...
                    return super.getStream(uri);
         private void exhaustInputStream(final InputStream inputStream) {
                  // Since InputStream.read() blocks, exhast the stream in a separate thread
                  new Thread() {
                       public void run() {
                            try {
                                 while(inputStream.read() >= 0) {
                                      // Just throw the bytes away
                            catch(IOException e) {
                                 e.printStackTrace();
                  }.start();
             }

    Read this article
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Running jar in unix using runtime exec command

    Hi, i want to run a jar in unix with the runtime.exec() command,
    but i couldn't manage to do it
    Here is the code
    dene = new String[] {"command","pwd","java tr.com.meteksan.pdocs.pdf.html2pdf "+ f.getAbsolutePath() + " " + pdfPath};
              System.out.println("Creating PDF");
              FileOutputStream fos = new FileOutputStream(new File(pdfPath));
              Runtime rt = Runtime.getRuntime();
              for(int i = 0 ; i < dene.length ; i++)
                  System.out.println("komut = "+dene);
              Process proc = rt.exec(dene);
              // any error message?
              StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
              StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos); // kick them off
              errorGobbler.start();
              outputGobbler.start();
              // any error???
              int exitVal = proc.waitFor();
              System.out.println("ExitValue: " + exitVal);
              fos.flush();
              fos.close();
    when i run this program, the exit value of the process is 0
    can you tell me whats wrong?

    i changed the string to be executed to:
                             dene = new String[] {"sh","-c","java -classpath \"" + Sabit.PDF_TOOL_PATH
                                  + "avalon-framework-4.2.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "batik-all-1.6.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-io-1.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-logging-1.0.4.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "fop.jar:" + Sabit.PDF_TOOL_PATH + "serializer-2.7.0.jar:"
                                  + Sabit.PDF_TOOL_PATH + "Tidy.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xalan-2.7.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "xercesImpl-2.7.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xml-apis-1.3.02.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xmlgraphics-commons-1.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "html2pdf.jar:\" tr.com.meteksan.pdocs.pdf.html2pdf "
                                  + f.getAbsolutePath() + " " + pdfPath};     
    and it works now ;)
    thanks...

  • How to display Runtime.exec() command line output via swing

    Hi all, I'm new to java but have a pretty good understanding of it. I'm just not familiar with all the different classes. I'm having trouble capturing the output from a command I'm running from my program. I'm using Runtime.exec(cmdarray) and I'm trying to display the output/results to a JFrame. Once I get the output to display in a JFrame, I'd like it to be almost like a java command prompt where I can type into it incase the command requires user interaction.
    The command executes fine, but I just don't know how to get the results of the command when executed. The command is executed when I click a JButton, which I'd like to then open a JFrame, Popup window or something to display the command results while allowing user interaction.
    Any examples would be appreciated.
    Thank you for your help in advance and I apologize if I'm not clear.

    You can get the standard output of the program with Process.getInputStream. (It's output from the process, but input to your program.)
    This assumes of course that the program you're running is a console program that reads/writes to standard input/output.
    In fact, you really should read from standard output and standard error from the process you start, even if you're not planning to use them. Read this:
    When Runtime Exec Won't

  • Running ftp from runtime exec()

    How would I run ftp from exec()? Can I run a script that is ftping from exec()? Why would anyone go through the trouble of writing their own ftp code, if you can just call a script from the exec() method? I am going to be running ftp from a servlet to send a file to a mainframe, where it will run and create an xml file that the servlet will then post to the screen. should I be using java's ftp commands, or will my script way work fine?
    Thanks

    How would I run ftp from exec()?Like any other program. It would be good to read the article http://www.javaworld.com/jw-12-2000/jw-1229-traps.html first to get it right the first time.
    Can I run a script that is ftping from exec()?I don't see any objections.
    Why would anyone go
    through the trouble of writing their own ftp code, if
    you can just call a script from the exec() method?Good question. 1) you are making your application platform dependent by using a platform depenent program 2) Runtime.exec() can't be used in applets but ftp over a socket connection is possible 3) There are already good packages for it (eg. at www.fooware.com) written for it so you don't need to write anything yourself (and 4: just because it's fun!)
    I am going to be running ftp from a servlet to send a
    file to a mainframe, where it will run and create an
    xml file that the servlet will then post to the
    screen. should I be using java's ftp commands, or
    will my script way work fine?
    If you have a working script and you know you will work on only one platform calling a script with exec will be just fine.

  • Make can't recursively call Make when run from Runtime.exec (for some user)

    This one is a little complicated. The afflicted platform is Mac OS X. It works fine on Linux, it seems, and even then, it does work for some Mac OS X users...
    First, the setup. I have a Java program that has to call GNU Make. Then, GNU Make will recursively call Make in some subdirectories. This results in the following Java code:
    String make = "make"; //on windows, I have this swapped with "mingw32-make"
    String workDir = ...; //this is programmatically detected to be the same folder that the parent Makefile is in
    Runtime.getRuntime().exec(make,null,workDir);This calls make on a Makefile which has the following line early on to be executed (this is only a snippet from the makefile):
    cd subdirectory && $(MAKE)When I fetch the output from the make command, I usually get what I expect: It cd's to the directory and it recursively calls make and everything goes smoothly.
    However, for one particular user, using Mac OS X, he has reported the following output:
    cd subdirectory && make
    /bin/sh: make: command not found
    make: *** [PROJNAME] Error 127Which is like, kinda hurts my head... make can't find make, apparently.
    I've gotten some suggestions that it might be due to the "cd" command acting wonky. I've gotten other suggestions that it may be some strange setup with the env variables (My Mac developer is implementing a fix/workaround for 'environ', which is apparently posix standard, but Mac (Mr. Posix Compliance...) doesn't implement it. When he finishes that, I'll know whether it worked or not, but I get the feeling it won't fix this problem, since it's intended for another area of code entirely...
    Also worth mentioning, when the user calls "make" from the terminal in said directory, it recurses fine, getting past that particular line. (Later on down the road he hits errors with environ, which is what my aforementioned Mac dev is working on). Although calling "make" by hand is not an ideal solution here.
    Anyways, I'm looking for someone who's fairly knowledgeable with Runtime.exec() to suggest some way to work around this, or at least to find out that perhaps one of the User's settings are wonked up and they can just fix it and have this working... that'd be great too.
    -IsmAvatar

    YoungWinston
    YoungWinston wrote:
    IsmAvatar wrote:
    However, for one particular user, using Mac OS X, he has reported the following output:One particular user, or all users on Mac OS?In this case, I have two mac users. One is reporting that all works fine. The other is reporting this problem.
    cd subdirectory && make
    /bin/sh: make: command not found
    make: *** [PROJNAME] Error 127Which is like, kinda hurts my head... make can't find make, apparently.If that is being reported on the command line, then I'd say that make wasn't being found at all.If make isn't being found, then who's interpreting the Makefile?
    It's also just possible that the make script on Mac isn't correctly exporting its PATH variable, though it seems unlikely, since this would surely have been reported as a bug long ago.
    I've gotten some suggestions that it might be due to the "cd" command acting wonky...Also seems unlikely. 'cd' has been around since shortly after the K-T extinction event.
    WinstonBy "acting wonky", I mean being given a bad work directory or some such, such that it's not changing to the intended directory.
    Andrew Thompson
    Andrew Thompson wrote:
    (shudder) Read and implement all the recommendations of "When Runtime.exec() won't" (http://www.javaworld.com/jw-12-2000/jw-1229-traps.html).
    Already read it. I already know the dreadful wonders of Runtime.exec. But in this case, it's been working fine for us up until one Mac user reported that make can't find make.
    Also, why are you still coding for Java 1.4? If you are not, use a ProcessBuilder, which takes a small part of the pain out of dealing with processes.Usually I do use a ProcessBuilder. I noticed that it usually delegates to Runtime.exec() anyways, and seeing as I didn't need any of the additional functionality, I decided to just use Runtime.exec() in this particular case.
    jschell
    jschell wrote:
    So print thos env vars, in your app and when the user does it.I'll look into that. It's a good start.
    -IsmAvatar

  • Execute java class from a batch file called from runtime.exec

    Hi.
    I don´t know if this question fits here.
    I wan´t to execute a batch file (on Win XP) with runtime.exec. That batch file will execute another java program.
    I have the following code:
    Resolutor.java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    public class Resolutor {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Runtime r = Runtime.getRuntime();
              //String[] command = { "cmd.exe", "/C",".\\lanzar.bat .\\ .\\ 001.res:001.dtt" };
              String[] command = { "cmd.exe", "/C",".\\tarea\\lanzar.bat " + args[0] + " " + args[1] + " " + args[2]};
              try {
                   //Process proceso = Runtime.getRuntime().exec("lanzar.bat");
                   Process proceso = Runtime.getRuntime().exec(command);
                   InputStream stderr = proceso.getErrorStream();
                InputStreamReader isr = new InputStreamReader(stderr);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                System.out.println("<ERROR>");
                while ( (line = br.readLine()) != null)
                    System.out.println(line);
                System.out.println("</ERROR>");
                   int exitVal = proceso.waitFor();
                   System.out.println("EXITVAL: " + exitVal);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }lanzar.bat
    java Lanzador %1 %2 %3Lanzador.java
    import java.util.Vector;
    public class Lanzador {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Repetitiva rpt=new Repetitiva();
              String rutaFicheros=args[0];
              String rutaResultado=args[1];
              String[] ficheros=args[2].split(":");
              Vector<String> ficheroDatos=new Vector<String>();
              for(int i=0;i<ficheros.length;i++){
                   ficheroDatos.add(ficheros);
                   System.out.println(ficheros[i]);
              System.out.println("RUTA DE FICHEROS: " + rutaFicheros);
              System.out.println("RUTA DE RESULTADOS: " + rutaResultado);
              System.out.println("CALCULAR");
              rpt.setRepetitiva(ficheroDatos, rutaFicheros, rutaResultado);
              rpt.calcular();
    }I´ve got Resolutor.class in /res and the other two files (and the rest of the files for running) in /res/tarea.
    If I execute /res/tarea/lanzar.bat from the command line everything works fine, it calls java and runs lanzador without problem.
    The problem comes when I try to execute the batch file via Resolutor.class. It executes the batch file without problem, but it throws a *java.lang.NoClassDefFoundError: Lanzador* when launching the new java application.
    Any ideas of how can I solve that problem. (It must do it via batch file).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Well, I tried putting in the bat file java -classpath .\tarea Lanzador %1 %2 %3 and didn´t work.
    I ve tried the bat modification, and the directory in x.txt is k:\res instead of k:\res\tarea.
    I´ve tried to modifiy it to java .\tarea\Lanzador and didn´t work so I have put a cd like the following and it appears to work.
    cd tarea
    java Lanzador %1 %2 %3Thanks for the replies.

  • Accesing environment variables from Runtime.exec()

    Hi All,
    I have a problem for which I need help. I have a property BLAH set to "abc" in my ~/.bashrc. My programme looks as following.
    Runtime rt = Runtime.getRuntime();
    String command="java -Dext.prop=${BLAH} Test1";
    //Even following also dont work I removed curly braces
    // String command="java -Dext.prop=$BLAH Test1";
    try {
    rt.exec(command);
    } catch (IOException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    I just want to set the value of environment variable to a property "ext.prop" and in class Test1 I would like to access it as System.getProperty("ext.prop"). The problem is that the value of System.getProperty("ext.prop") is $BLAH instead of "abc" which I set in my ~/.bashrc.
    If I execute the same command ("java -Dext.prop=${BLAH} Test1") from command prompt then I don't have any problem. I tried in another way also that is
    Edited by: ragsger on Dec 22, 2008 12:59 PM
    Edited by: ragsger on Dec 22, 2008 1:00 PM

    Replacing $BLAH with the value of the environment variable BLAH is handled by the shell and since you don't call a shell, you'll have to do that on your own.
    System.getenv("BLAH") will get the value.

  • Runtime.exec(command)

    hi experts,
    I am trying to execute a set of commands from java program
    eg: from command prompt
    java CommandExecutor c:\winnt\notepad.exe c:\some.exe c:\onemorecommand.exe
    and inside the CommandExecutor main method..
    public static void main(String []arg)
    for(i = 0; i < arg.length; i++)
    Runtime.getRuntime().exec(arg(i));
    the above code is executing all the command one after the other, but I want to execute the above commands squentially, i.e I want to execute the second command only after finishing the first command and the third after finishing the second and so on depending upon the arguments passed, how can I acheive this...
    I have tried to use the Process which is returned by the exec(arg) method but the exitValue() returns same value before execution and after execution.
    thanks,
    krishna

    This is the code I use for this very purpose and it works great. Here you go:
    * Wrapper for Runtime.exec
    * No console output is generated for the command executed.
    * Use <code>process.getOutputStream()</code> to write data out that will be used as
    * input to the process. Don't forget to include <code>\n</code> <code>\r</code>
    * characters the process is expecting.
    * Use <code>process.getInputStream</code> to get the data the process squirts out to
    * stdout.
    * It is recommended to wrap this call into a seperate thread as to not lock up the
    * main AWT event processing thread. (generally seperate threads are needed for both
    * the STDOUT and STDIN to avoid deadlock)
    * @param theCommand fully qualified #.exe or *.com command for windows etc.
    * @see   exec, shell, command, cmd, forDOS, forNT
    public static Process exec( String theCommand, boolean wait )
         Process process;
         try
              process = Runtime.getRuntime().exec( theCommand );
         catch ( IOException theException )
              return null;
         if ( wait )
              try
                   process.waitFor();
              catch ( InterruptedException theInterruptedException )
         return process;
    }

  • Runtime exec command parameters with SSH

    hey,
    Im trying to run a unix command using Process proc = Runtime.getRuntime().exec(command);
    It works fine until I tried to combine it with multiple commands.
    For example, I'm trying to run:
    ssh [email protected] 'ls -al'
    This returns a exit value of -1, command not found.
    ssh [email protected] ls works fine so I suspect its related to the extra parameters.
    I checked the Javadoc page for exec:
    The command argument is parsed into tokens and then executed as a command in a separate process. The token parsing is done by a StringTokenizer created by the call:
    new StringTokenizer(command)
    As expected, it tokenized:
    ssh
    [email protected]
    'ls
    -al'
    Is there any way to bypass this default tokenization by exec to include quotes as one token?
    If anyone has any ideas, let me know! Thanks!

    thanks, solves that part.. but if i use execute command with ssh and bsub(a clustering job queue-submitter), it does ot return the correct value.
    For example, if i do ssh [email protected] bsub -I ls using exec and the waitFor() method, the waitFor waits indefinitely.
    I can tell it ran the job and ended, because i checked via bjobs and it finished. So why isn't the java app getting the exit code from waitFor() back?
    If I run the program on the targeted machine, bsub -I ls, it works correctly.
    If i type in the console, ssh [email protected] bsub -I ls, it returns back the results correctly.
    info regarding bsub and bjobs here http://www.ncsa.uiuc.edu/UserInfo/Resources/Hardware/XeonCluster/Doc/Jobs.html

  • Runtime.exec() command to open default pdf reader

    Hello
    I want to launch a pdf-file (from within the code) on the system default pdf-reader. Can I somehow retrieve the path to the default pdf-reader and use it like this:
    String pdfReaderPath = retrievePDFreaderpath(); // ????
    String filename = new String("E:\\Test.pdf");
    String[ ] open = {pdfReaderPath , filename};
    try {
    Process proc = Runtime.getRuntime().exec(filename);
    } catch (IOException e) {
    e.printStackTrace();
    Thank you!

    I am new to java programming. I am trying to launch a pdf file from a share drive, but I am getting the following error.
    C:\Misc Java>java PdfExec
    java.io.IOException: CreateProcess: I:/Bass/FRMGEB01.2005 0204 Invoice.pdf erro
    =193
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at PdfExec.main(PdfExec.java:24)
    Following is my simple code.
    import java.io.*;
    public class PdfExec {
    public static void main(String argv[]) {
    try {
    Process proc = Runtime.getRuntime().exec("//whmax/WHMAX-COMMON/Bass/FRMGEB01.2005 0204 Invoice.pdf");
    catch (IOException e) {
    e.printStackTrace();
    Any help will be appreciated. Thx!

  • Running C++ application from Runtime.exec

    Hello everybody
    I am trying to run a c++ executable file(myap.exe) using Runtime.getruntime().exec("myap"), nothing happend!.
    Can anyone help me please.

    Where is located the file 'myapp.exe' ?
    If not in directory that is in 'PATH' varable, you need to use :
    Runtime.exec(String command, String[] envp, File dir)
    Executes the specified string command in a separate process with the specified environment and working directory.
    Floweb

  • Displaying input from Runtime.exec()

    Hi there, after all my troubles, I'm finaly able to get all the input from the unix machine using Runtime.exec() and to have it come out pretty quick. My new problem now is that I need to take that input and display it onto a textPane. Anyone who can help me do that? here is the code I have written, along with the method I use called setPaneText():
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.type = type;
    public void run()
    try
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (Exception ioe)
    ioe.printStackTrace();
    private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    Object source = evt.getSource();
    String serverComm;
    serverComm = "";
    serverComm = pp.getServerComm();
    if(source == jMenuItem13)
    try
    String osName = System.getProperty("os.name");
    Runtime rt = Runtime.getRuntime();
    Process commandReturn = rt.exec(serverComm + " /usr/local/bin/dlgexec pd_rm_cm trashcan");
    //StreamGobbler errorGobbler = new
    //StreamGobbler(commandReturn.getErrorStream(), "ERROR");
    StreamGobbler outputGobbler = new
    StreamGobbler(commandReturn.getInputStream(), "OUTPUT");
    //errorGobbler.start();
    outputGobbler.start();
    int exitVal = commandReturn.waitFor();
    System.out.println("exitVal = " + exitVal);
    if(exitVal == 0)
    System.out.println("inside the trashcan if");
    int cnt = 0;
    String outText []= new String [10000];
    BufferedReader buffy = new BufferedReader(new InputStreamReader(outputGobbler.is));
    while((outText[cnt]=buffy.readLine()) != null)
    cnt++;
    if(cnt == 9000)
    break;
    TextAreaPanel tp;
    tp = new TextAreaPanel();
    for(int cnt2 = 0; cnt2 < cnt; cnt2++)
    String temp;
    temp = outText[cnt2] + "\n";
    tp.setPaneText(temp);
    jPanel1.removeAll();
    jPanel1.add(tp, BorderLayout.CENTER);
    jPanel1.validate();
    this.repaint();
    catch(Throwable t)
    t.printStackTrace();
    and here is the method that I call
    public void setPaneText(String message)
    jTextArea1.setEnabled(true);
    //jTextArea1.setEditable(false);
    String outText = message;
    jTextArea1.setText(message);
    jScrollPane1.setViewportView(jTextArea1);
    //return outText;
    String message;

    @Op. Please learn how to use code formatting when you post code:
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Rsync from Runtime.exec

    I'm trying to run following command with Runtime.exec:
    rsync -auz sourceHost:'path1 path2' tmpSo I have following code to run this command:
    command[0] = "rsync";
    command[1] = "-auz";
    command[2] = "sourceHost:'path1 path2'";
    command[3] = "tmp";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);
    InputStream stdin = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ( (line = br.readLine()) != null) {
          System.out.println(line);
    stdin = proc.getInputStream();
    isr = new InputStreamReader(stdin);
    br = new BufferedReader(isr);
    line = null;
    while ( (line = br.readLine()) != null) {
          System.out.println(line);
    int exitVal;
    try {
          exitVal = proc.waitFor();
    } catch (InterruptedException e) {
          throw new IOException(e.getMessage());
    if (exitVal != 0) {
          throw new IOException("Exit value was " + exitVal + " that means an error occured" +
              " during rsync call");
    }What happens is that when I run the code rsync gives me following error:
    rsync: link_stat "path1 path2" failed: No such file or directory (2)
    rsync error: some files could not be transferred (code 23) at main.c(812)
    client: nothing to do: perhaps you need to specify some filenames or the --recursive option?
    java.io.IOException: Exit value was 23 that means an error occured during rsync call
            at RSyncTest.rsyncBinaryData(RSyncTest.java:156)
            at RSyncTest.main(RSyncTest.java:80)Can anyone think of what's wrong here?
    Regards and Thanks,
    David

    In Java version 1.3 (and later) method exec() of class Runtime returns a Process instance when invoked. The process object returned is what you need to manage.

Maybe you are looking for

  • Bursting Scheduling Error - Urgent

    Hi, Can anyone help? I have scheduled a report for bursting and see the following errors in schedule history: Error!! Can not find the delivery details for the delivery Id :Commercial Data Ltd When I check the bursting query this delivery id(Commerci

  • Steps for creation of DSO in BI7.....

    Hi, Can anyone help me out with the steps for creation of DSO in BI7..... Points will be assigned... Cheers Shankar

  • Export in 1.1 is MUCH brighter

    In LR 1.1 I can take a jpeg, .psd, or raw file and color correct it. BUT, when I do an export to a jpeg the images are significantly brighter. No color shift, but brighter. Viewing the exported images in any tool I've tried shows the same significant

  • How to track transporter of scheduled transport (TMS)?

    Prior to audit requirement,basis has been asked by auditor to provide all the selected transport lists and the name of the transporters for each selected transports.The problem is,most of the transports have been done through TMS (Schedule) and trans

  • STO WITH EXCISE, RG23A - Register is not updating

    Hai experts, I have created stock transfer order, with reference to that order i have issued material to another plant. with reference to this document number i have created excise document in J1IS & J1IV... It has to update in RG23A Part II.. It is