RSH, Runtime.exec() & Exitcodes

hi
I am using RSH.exe on a Windows machine, which is used to access my server machine, running AIX 4.3. All I want to do is create a directory on the server that is required by the my Java program, so that the files that the program will be copying to the server can be placed into the new directory created. I can accomplish all this. To execute the RSH.exe I use Runtime.exec() method. However, when I use the Process.waitFor() method the program hangs... therefore no exit value is returned and it is this exit value that I require! The output from the process is displayed for both normal output and error output... can anyone shed any light onto this situation???? pleeeeeease! it is really wrecking my head now....
Regards,
Finbarr.

hi
unfortunately the thread idea has yielded no results! the problem still exists...... it is driving me mad!
Finbarr.

Similar Messages

  • How to make Runtime.exec call Linux exec?

    Howdy,
    I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs.
    Here's the command:
    Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;");
    It's failing, not sure why, the exitCode is 1 instead of 0. I'm not sure if it's because I have to escape the '\' character, or if it's because I am calling Linux's 'exec' function within a Java exec() call, or something else entirely.
    The easiest thing to do would be to just use rm, but that doesn't seem to be an option. With rm it seems to be all or nothing -- If I try:
    rm -rf *.vcs
    it fails if it doesn't find a file with that extension in the start directory (even though I've specified -r). But if I enter:
    rm -rf *
    it nukes my directories AND files, something I don't want to happen. I realize this is a Linux thing, I'm just explaining it here as background, just in case.
    Anyway, so is there a way to do this? Perhaps with another system call, without using Linux's exec()?
    Many thanks
    Bob

    import java.io.*;
    public class ExecutingALinuxCommand
        static class PipeInputStreamToOutputStream implements Runnable
            PipeInputStreamToOutputStream(InputStream is, OutputStream os)
                is_ = is;
                os_ = os;
            public void run()
                try
                    byte[] buffer = new byte[1024];
                    for(int count = 0; (count = is_.read(buffer)) >= 0;)
                        os_.write(buffer, 0, count);
                catch (IOException e)
                    e.printStackTrace();
            private final InputStream is_;
            private final OutputStream os_;
        public static void main(String[] args)
            try
                String dir = System.getProperty("user.home") + "/work/dev";
                String[] command = {"sh","-c", "find " + dir + " -name '*.java' -exec grep -l Runtime {} \\;"};
                final Process process = Runtime.getRuntime().exec(command);
                new Thread(new PipeInputStreamToOutputStream(process.getInputStream(), System.out)).start();
                new Thread(new PipeInputStreamToOutputStream(process.getErrorStream(), System.err)).start();
                int returnCode = process.waitFor();
                System.out.println("Return code = " + returnCode);
            catch (Exception e)
                e.printStackTrace();
    }

  • Problem in Runtime.exec()

    I am trying to launch a new java application from my java program like this-:
    import java.io.*;
    public class test123{
    //String userStr="";
                public static void main(String args[]) throws Exception{
                        Process p = Runtime.getRuntime().exec("java JavaExec",null,currentDir);
                        Thread.sleep(10000);
                        System.out.println("After Destroy");
    } The JavaExec file�s code is -:
    import java.io.*;
    import org.apache.log4j.Logger;
    public class JavaExec
                 static Logger logger = Logger.getLogger("JavaExec.class");
    public static void main(String args[])
    try
                Runtime runtime = Runtime.getRuntime();
                            Process process = runtime.exec("notepad");
                int exitCode=0;
                while(true)
                            //logger.info("Inside the infinite while loop in javaexec");
                            try
                                        exitCode = process.exitValue();
                                        System.out.println(exitCode);
                                        process.destroy();
                                        process = runtime.exec("notepad");
                            catch(IllegalThreadStateException itse)
                                        System.out.println("Inside exception");
    } catch (Throwable t)
    t.printStackTrace();
    }Notepad opens when I execute the test123 class but instead of remaining open even if I close it , I am able to close notepad. The JavaExec only starts processing again when my main quits.
    Please let me know the solution to this problem.....
    Thanks in Advance
    Inder Jeet Singh

    Convoluted at best. You don't need that loop, just useexitCode = process.exitValue();and it will block until notepad exits.
    P.S. Why a Runtime.exec() executing a Java program that does a Runtime.exec() on notepad?

  • Runtime.exec(), so much fun

    I'm at the bang your head on the monitor stage of this.
    I have some executables written in C that I need to be able to executed. They require an input file for processing and generate an output file with results, no big deal.
    They both run great from a command prompt. (I'm running on linux with j2sdk1.3.0 by the way)
    Now if I call one of them with Runtime.exec(), it runs perfectly as expected. Everything goes in, Everything comes out, Everyone is happy.
    If I call the other, It says it runs, I get an exit value of 0, the output file is created, but empty.
    I thought I could open a shell with Runtime and then try to get it to run from there to see if it would make any difference, but I was unable to get the shell to call the executables to run with the arguments for input. There is something weird with the way Runtime feeds the strings to the shell. I tried a couple variations.
    Then I thought, what the hell, I wonder if I can write a shell script that calls the executables and see what I get from there. So I wrote a little script that just calls the executable with one little hard coded input, just to see if it would run. Run the script from a command prompt, works great and as expected. Try to call the simple little script from Runtime.exec() and I get a segmentation fault.
    At this point, I'm almost giving up on an easy answer for what in theory should be taking a few lines of code.
    If anybody has a clue on how to approach this or what might be causing this, please let me know.
    for the whole saga
    http://www.javaranch.com/ubb/Forum13/HTML/000198.html
    http://www.javaranch.com/ubb/Forum34/HTML/001360.html
    Any response here would be appreciated.

    I guess clicking on links and reading is too much to
    ask.I admit I didn't read the thread there. Shame on me.
    But i did this litle test.
    Here I have a C program that reads from a file two numbers and writes some lines to another. The names are passed in command line.
    #include <stdio.h>
    #define NAME "[first test program]"
    int main(int argn, char** args) {
      FILE* in = NULL;
      FILE* out = NULL;
      int exitCode = 0;
      int nLoops = 0;
      int nSec = 0;
      int i;
      if(argn < 3) {
        fprintf(stderr, "%s usage: %s inFile outFile\n", NAME, args[0]);
        exitCode = 1;
        goto _exit;
      in=fopen(args[1], "rt");
      if(in == NULL) {
        fprintf(stderr, "%s Cannot open file %s\n", NAME, args[1]);
        exitCode = 2;
        goto _exit;
      out=fopen(args[2], "wt");
      if(out == NULL) {
        exitCode = 2;
        goto _exit;
      fscanf(in, "%d", &nLoops);
      fprintf(stdout, "%s read %d loops from %s\n", NAME, nLoops, args[1]);
      fflush(stdout);
      fscanf(in, "%d", &nSec);
      fprintf(stdout, "%s read %d seconds to sleep from %s\n", NAME, nSec, args[1]);
      fflush(stdout);
      for(i=0; i<nLoops; i++) {
        fprintf(stdout, "%s try to write line %d on %s ... ", NAME, i, args[2]);
        fflush(stdout);
        sleep(nSec);
        fprintf(out, "%s line number %d\n", NAME, i);
        fprintf(stdout, "done\n");
        fflush(stdout);
      fflush(out);
    _exit:
      if(in != NULL) fclose(in);
      if(out != NULL) fclose(out);
      return exitCode;
    }I created an executable c1 and the I modified the NAME and created another executable c2.
    The I wrote a small java test class :
    import java.io.*;
    public class test {
        public static void main(String[] args) {
         String[] cmd1 = { "./c1", "input1", "out1" };
         String[] cmd2 = { "./c2", "input2", "out2" };
         Runtime r = Runtime.getRuntime();
         try {
             Process p1 = r.exec(cmd1);
             Process p2 = r.exec(cmd2);
             BufferedReader r1 =
              new BufferedReader(new InputStreamReader(p1.getInputStream()));
             BufferedReader r2 =
              new BufferedReader(new InputStreamReader(p2.getInputStream()));
             String l1 = r1.readLine();
             String l2 = r2.readLine();
             while(l1!=null || l2!=null) {
              if(l1 != null) System.out.println("from java proc 1:\t" + l1);
              if(l2 != null) System.out.println("from java proc 2:\t" + l2);
              l1 = r1.readLine();
              l2 = r2.readLine();
         } catch (Exception ex) {
             ex.printStackTrace();
    }The imput files contains on a single line the number of lines to write on the output file and a sleep time between lines, like:
    100 1This test runs fine on my linux box.
    I have a RedHat 7.0 on a PIII, kernel 2.2.16-22 .
    You can try and see if it is working on your box. I think it will. My guess is that the problem is somehow on the second c program.
    I didn't read the other thread, so maybe the answer is there, but I'll ask: the problem is with a specific program, or allways happen with the second that you run?
    Anyway, it will be nice if you can isolate the problem in three small source files and send them here.
    Regards,
    Iulian

  • Runtime.exec and exitValue

    hi all,
    i know about the miolion of topics about this object, but i've a question a little bit more specific.
    I have a part of my code that needs to launch external command . I want to save the output of these commands, but i have to minimize the number of thread spawned. In addtion, i cannot know the number of command launched, so the thread number will became an important factor to bound.
    At the same time i need to write something at the end of the output file, so i need to know when the process launched has terminated.
    What i did:
    //  main
    //  here create a thread for process control
    //   procControlThread
    public void launchCommand(String cmd, String file, long ID){
      Process p  = Runtime.exec(cmd+" 1 >> "+file);
       procControlThread.addObj(p,file).
    // in the procControlThread
    public void addObj(Process p, String file){
         synchronized(struct){
              storeSomeWhere(p,file);
    public void run(){
       Iterator i;
      while(boolean){
         synchronized(struct){
            i=struct.iterator();
             while(i.hasNext()){
                MyObj o = (MyObj)i.next();
                 int exitCode;
                  try{
                    exitCode=o.getProcess().exitValue()
                   }catch(IllegalThreadStateException e){
                          // process has not yet finished
                         continue;
                    // process has finished
                    // print in the file where is logged
                   //  the stdout fo the command
                    printSomething(o.getFile(),exitCode);
                     remove(o);
           Thread.sleep(10*1000);    
    // where printSomething
    // create  a Printwriter using a FileOutputStream.well, sometimes i get FileNotFoundException in the printSomething where is mentioned that the file is currently owned by another process.
    do I miss something in the exit code?
    I should using Process.WaitFor()? [ in this case I have to create one thread for controlling one process!]
    -- jdk 1.3.1
    Really thanks in advance.
    T.

    Seems like it should work. Obviously the code you posted is not the same as what you're running though (as it can't compile e.g. while (boolean)), so I'd wonder about what you're really doing.

  • BufferedReader blocks when using Runtime.exec()

    I'm executing an external process in Linux (RH 8.0) using the Runtime.exec() method and then setup two threads to read the standard and error output of the process. Most of the time this works great but every now and then the readers block and the process never exit. I even tried seting up a timer task that will close the BufferedReader after 20 seconds but that's not enough to unblock the reader - the external process is a dummy shell script which for now just outputs a single line. Does anybody have any idea why that would happen? Any help would be appreciated!
    Cheers,
    /Francis
    P.S. Here's a snippet of the code:
    public class ProcessRunner {
      private Process _process = null;
      private StreamGobbler _errorGobbler = null;
      private StreamGobbler _outputGobbler = null;
      private String[] _commandArgs;
      public ProcessRunner(String[] args) {
        _commandArgs = args;
      public int runCommand()
        throws IOException {
        int exitCode = -1;
        _process = Runtime.getRuntime().exec(_commandArgs[0]);
        // start up stream gobblers (inspired from javaworld)
        _outputGobbler = new StreamGobbler(new BufferedReader(new InputStreamReader(_process.getInputStream())));
        _outputGobbler.setDaemon(true);
        _errorGobbler = new StreamGobbler(new BufferedReader(new InputStreamReader(_process.getErrorStream())));
        _errorGobbler.setDaemon(true);
        _outputGobbler.start();
        _errorGobbler.start();
        try {
          exitCode = _process.waitFor(); // *** THIS NEVER RETURNS ***
          if (_outputGobbler != null) {
            _outputGobbler.join();
          if (_errorGobbler != null) {
            _errorGobbler.join();
        } catch (InterruptedException exc) {
          //ok, continue
        return exitCode;
      class StreamGobbler extends Thread {
        BufferedReader reader;
        StreamGobbler(BufferedReader reader) {
          this.reader = reader;
        public void run() {
          try {
            final int buffersize = 256;
            byte[] bytes = new byte[buffersize];
            String line = null;
            while((line = reader.readLine()) != null) {    // ***THIS ALSO BLOCKS ***
              baos.write(line.getBytes(), 0, line.length());
          } catch (IOException ioe) {
            // Do something here
          } finally {
            reader.close();
            reader = null;

    I use this type of thing in my code using JDK1.3.1. Only difference is I don't use set up the readers in threads. I suspect you have a thread deadlock, but I can't see why. Do you have to have the i/o stream readers in the thread?

  • Runtime.exec(): VM creates batch executions???

    I wrote an application that performs a task within a loop. Therefore i setup up a prograssbar in my GUI. during testing, the progressbar showed nice progress by just perforing a Thread.sleep() as the task. Then i replace the Thread.sleep() with the real task that is execution of a system command:
                        Runtime rt = Runtime.getRuntime();
                        process = rt.exec(command);     
                        exitCode = process.waitFor(); //wait until system command returnsand suddenly the progressbar doesn't proceed but pops up at the and of the complete loop. First i thought it is a refresh problem of the progressbar, but after i insertet System.out, these System.outs within the loop also only get printed (all but the very first) at the end of the loop. Toggling between the execution tasks "Thread.sleep" and "Runtime.exec" also toggles "nice progress output" and "output all at the end of the loop".
    I wonder why this happens?

    At least, i can workaround this because my system command throwed an IOException. With the correct command, it worked. But the effect still occurs, because I added a System.out in the catch clause and when using the wrong command (that cause the IOException), even those System.outs were printed in a batch way (all at wants) after all tasks finsihed. System.out.flush() didn't make any difference.

  • Runtime.exec() - how to open new window for new program?

    Hi,
    I have searched through the forums but haven't found an answer to this one yet. I am using runtime.exec() to start up a new java program. At first I thought it wasn't running properly but, after checking task manager, I have discovered that the new program I open runs, it is just completely invisible to me. I am wondering how I can get the new program to run in a command window or something where I can monitor it.
    Thank you for your help,
    Drew

    Thank you all. After trying to figure out why the start command wouldn't work in the runtime.exec() call(not an executable - I am a dolt), I tried putting it in a batch file and it worked perfectly. Thanks for your help,
    Drew

  • How to capture Runtime.exec() output? doesn't seem to work?

    This is the first time I've used Runtime.exec();
    Here's the code:
    Runtime rt = Runtime.getRuntime();
                process = rt.exec(jobCommand);
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line=null;
                while((line=input.readLine()) != null) {
                     System.out.println("OUTPUT: " + line);
                int exitVal = process.waitFor();
            } catch(Exception e) {
                 e.printStackTrace();
            }//end catchas you can see, this is just copied and pasted out of the standard example for this method.
    When it gets to the line:
    while((line=input.readLine()) != null)
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    what am i doing wrong here?
    thanks.

    Welcome to the forum!
    >
    as you can see, this is just copied and pasted out of the standard example for this method.
    >
    No one can see that - you didn't post a link to the example you said you copied.
    >
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    >
    No one can see what command you are talking about; you didn't post the commnd or even describe what output you expect to get.
    >
    what am i doing wrong here?
    >
    What you are doing wrong is not providing the code you are using, the command you are using or enough information about what exactly you are doing.
    No one can try to reproduce your problem based on what you posted.

  • 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

  • Using Runtime exec() to open and close process like java or javac

    Hi, I m a student who is learning IT and is wondering if
    Runtime exec() can run and stop commands like java and javac?
    Can someone post the code to do so here?Thank you

    Well, Here is my complete code:
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    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 (IOException ioe)
    ioe.printStackTrace();
    class Program implements Runnable
         Process proc;
    String args[];
         String[] cmd = new String[4];
         boolean isGone=false;
         public Program(String args[])
              this.args=args;
         public void run()
              if (isGone==true)
                   try
                        Runtime.getRuntime().exec(cmd).destroy();
                   catch(IOException e)
                        System.out.println("Error: "+e.toString());
                   System.out.println("User abort");
         public void start(String args[])
              if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[3] = args[0];
    else if( osName.equals( "Windows 95" ) ||osName.equals( "Windows 98" ))
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
                        cmd[3]=args[1];
    Runtime rt = Runtime.getRuntime();
    // System.out.println("Execing " + cmd[0] + " " + cmd[1]
    // + " " + cmd[2]+" "+args[1]);                                    
    proc = rt.exec(cmd);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    // int exitVal = proc.waitFor();
    //System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
         public void destroy()
              isGone=true;
    class test1 implements ActionListener
         String s[]={"c:\\jdk1.3\\bin\\java.exe","ContactProcessor1"};
         GUI g=new GUI();
              Program p=new Program(s);
         public test1()
              //didnt work
              g.getStart().addActionListener(this);
              g.getStop().addActionListener(this);
              g.show();
         public void actionPerformed(ActionEvent e)
              if (e.getSource()==g.getStart())
                   p.start(s);
                   p.run();
              if (e.getSource()==g.getStop())
                   p.destroy();
                   p.run();
         public static void main(String args[])
              test1 t = new test1();
    class GUI extends JFrame
         JButton start;
         JButton stop;
         public GUI()
              super();
              getContentPane().setLayout(new FlowLayout());
              start=new JButton("start");
              stop=new JButton("stop");
              getContentPane().add(start);
              getContentPane().add(stop);
              setSize(100,100);
         public JButton getStart()
              return start;
         public JButton getStop()
              return stop;
    }

  • Error in opening a file with name in chinese characters with Runtime.exec

    The issue at hand is when I try to open a file with file name containing chinese characters in a localized environment in Windows through the following java code:
    Runtime.exec("rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}");
    the following error is thrown by windows.
    Cannot open file "C:\??.txt".
    with the exception
    java.io.IOException: CreateProcess: [Ljava.lang.String;@f5da06 error=2
            at java.lang.Win32Process.create(Native Method)
            at java.lang.Win32Process.<init>(Win32Process.java:66)
            at java.lang.Runtime.execInternal(Native Method)
            at java.lang.Runtime.exec(Runtime.java:566)
            at java.lang.Runtime.exec(Runtime.java:428)
            at java.lang.Runtime.exec(Runtime.java:364)
            at java.lang.Runtime.exec(Runtime.java:326)
            at Launcher.main(Launcher.java:26)
    When I try to use the same command (shown below) from the Windows Run command, the file opens sucessfully
    rundll32 SHELL32.DLL,ShellExec_RunDLL {File_With_FileName_containing_Chinese_character}
    Please suggest.
    Thanks in advance

    This may be a file association problem.  To solve that:
    In Windows 7:
    1. Right-click the file,
    2. Select "Open With" 
    select [Your Program Here]
    3. Check always use this program. 
    In Windows XP:
    1. Locate the file as you have described above
    2. Right click the file
    3. Select Open with from the pop-up menu
    4. Click Choose default program…
    5. Select Excel in the Recommended Programs box
    6. Check Always use the selected program to open this kind of file
    7. Click on OK.
    1.  Make Excel not available from Office 2007 listed under Programs and Features in Control Panel.
    2. Take a registry backup using the steps given here
    3. In the registry editor window expand HKEY_CLASSES_ROOT and navigate to .xls right and delete it.
    4. Exit Registry Editor
    5. Undo Step 1 to make Excel available.
    6.  Restart the computer and verify it the issue is fixed.
    If this answer solves your problem, please check Mark as Answered. If this answer helps, please click the Vote as Helpful button. Cheers, Shane Devenshire

  • The Runtime.exec methods doesn't work well on Solaris ???

    I have two threads and I set the different running time.
    I use Runtime.exec to a run the command and use Process to get the process.
    It works properly in the windows2000 platform.
    However, when I transfer the platform to Solaris...and run the program...
    Two threads always at the same time....It is very wired....I always debug
    for 2 days....
    (at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
    all of them don't work.....
    If I close the Runtime.exec..........Everything works well......)
    And I study the API. I found this message...
    The Runtime.exec methods may not work well for special processes on certain
    native platforms, such as native windowing processes, daemon processes,
    Win16/DOS processes on Win32, or shell scripts. The created subprocess does
    not have its own terminal or console.
    Could someone share her/his experience.....:(
    And if any other way I can run command inside java code instead of
    Runtime.exec.....???
    Please reply my mail to [email protected] I do appreciate your kindly &
    great help!!!!!!!!
    This is my code.......
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    * <p>ServerThread1</p>
    * <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
    class ServerThread1 extends Thread{
    private ServerAgent Sa;
    public ServerThread1 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa; file://Assign ServerAgent reference Sa
    public void run(){
    while(true){
    try{
    Thread.sleep(5000);
    catch (Exception e){
    System.out.println("ServerThread1 fails");
    System.out.println("Thread1 is running.");
    try {
    Runtime rt1 = Runtime.getRuntime();
    Process proc1 = rt1.exec("mkdir"); ------>If I close
    rt1.exec , two threads works seperately...........:(
    catch (Exception e) {
    System.out.println("Thread1 Error");
    class ServerThread2 extends Thread{
    private ServerAgent Sa;
    public ServerThread2 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa;
    public void run(){
    while(true){
    try{
    Thread.sleep(15000);
    catch (Exception e){
    System.out.println("ServerThread2 fails");
    System.out.println("Thread2 is running.");
    try {
    Runtime rt2 = Runtime.getRuntime();
    Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
    the rt2.exe, two threads work seperately....
    catch (Exception e) {
    System.out.println("Thread2 Error");
    public class ServerAgent{
    private Vector v1 = new Vector();
    private Vector v2 = new Vector();
    private Hashtable currentData = new Hashtable();
    private static String startUpSwap = null;
    private static String startUpMem = null;
    public static void main(String[] arg) {
    ServerAgent s = new ServerAgent();
    ServerThread1 st1 = new ServerThread1("Thread1",s);
    ServerThread2 st2 = new ServerThread2("Thread2",s);
    st1.start();
    st2.start();

    If I close the Runtime.exec..........Everything works
    well......)You don't empty the output of the command, that blocks the process.
    A citation from
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Why Runtime.exec() hangs
    The JDK's Javadoc documentation provides the answer to this question:
    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.
    Try out something like this:
    String s;
    try {
       Process myProcess =
       Runtime.getRuntime().exec("ls -l"));
       DataInputStream in = new DataInputStream(
              new BufferedInputStream(myProcess.getInputStream()));
        while ((s = in.readLine()) != null) {
            out.println(s);
    catch (IOException e) {
        out.println("Error: " + e);
    }Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
    Regards,
    Marc

  • How to give path in Runtime. exec( )

    Hi,
    I am trying to create an user interface, in which, it should open a different file (for example, example.doc)when a button is clicked in the applet. let us say, the path for example.doc is "C:\\WINDOWS\\DeskTOP\\folder1".
    I tried with the following code
    Runtime.getRuntime().exec("C:\\WINDOWS\\Desktop\\folder1\\example.doc");
    but, when I click on the button it is not opening example file and I am getting an exception. I am using Runtime.exec() command for the first time.Anybody can help me with this???

    Since when was a document an executable? The main problem is many people think Runtime.exec () is the same thing as the command line. The answer is, it's not. Typing "example.doc" in the windows terminal emulator (also known as cmd.exe in Windows 2000/XP or command.com in others) will work because example.doc is opened with the application configured to open files with the ".doc" extension.
    However, files ending with ".doc" are not executables. If you wish to open a ".doc" file with the associated application, try this: Runtime.getRuntime ().exec ("cmd /c example.doc"); Not that I don't know if this will work with command.com as I haven't tried, but it should work with cmd.exe without problems.
    Hope it helps.
    Cheers

  • Runtime.exec() - Need to execute unix command through pipe

    I want to execute something like this from Runtime.exec() :
    tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
    If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
    How can I achieve this?

    The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
    Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
    Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

Maybe you are looking for