Runtime.exec lifecycle

I am trying to execute a client using the following code below. It works fine when i run as stand alone java program. I am familiar with the javaworld article "When Runtime.exec() won't" ...
Process p = Runtime.getRuntime().exec("\"c:\a b\\client.exe\" "\"some param\"""); //   "c:\a b\client.exe" "some param"
            InputStream in = p.getInputStream();
            InputStream err = p.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = br.readLine()) != null) {           }
            in.close();            br.close();
            br = new BufferedReader(new InputStreamReader(err));
            while ((line = br.readLine()) != null) {            }
            p.destroy();But when I incorporate it to a web application using jrun it crashes in windows, shows the debug dialog. I don't get any exceptions.
Any clues?

As has already been pointed out, you do need to follow the recommendations in the 'traps' article but you seem to have ignored two of them.
First, you don't read stdout and stderr in separate threads. You can use the control thread to read one of them and a separate thread to read the other. Even better, if your really don't care about the content of stdout and stderr then use ProcessBuilder and redirect stderr to stdout and read stdout as you currently do.
Second, you don't wait for the process to terminate. Even worse, you destroy() it! Don't do this. This is possibly why the process crashes! Always wait for the process to complete and always check the exit code.
Now not part of the 'traps' article but a bit of advice - when debugging a Runtime.exec() problem or a ProcessBuilder problem ALWAYS write the stdout and stderr out somewhere. It is a very very very useful bit of diagnostic information.

Similar Messages

  • 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.

  • 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.

  • How to capture output of java files using Runtime.exec

    Hi guys,
    I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
    import java.io.*;
    public class CmdExec {
      public CmdExec() {
      public static void main(String argv[]){
         try {
         String line;
         Runtime rt = Runtime.getRuntime();
         String[] cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
         Process proc = rt.exec(cmd);
         cmd = new String[2];
         cmd[0] = "javac";
         cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
         proc = rt.exec(cmd);
         //BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
         while ((line = input.readLine()) != null) {
            System.out.println(line);
         input.close();
        catch (Exception err) {
         err.printStackTrace();
    public class E {
        public static void main(String[] args) {
            System.out.println("hello world!!!!");
    }Please help :)

    Javapedia: Classpath
    How Classes are Found
    Setting the class path (Windows)
    Setting the class path (Solaris/Linux)
    Understanding the Java ClassLoader
    java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
    javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.

  • How to capture output from Runtime.exec() ?

    Hi,
    Well, the question is in the subject ...
    I'd like to capture the output of a process ran by Runtime.exec() in order to process it.
    thanks,
    ionel

    Okay ...
    Sorry for the post !
    I found the solution : Runtime.exec().getOutputStream()
    Thanks however
    ionel

  • 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();
    }

  • Runtime.exec() fails sometime to execute a command

    Hello,
    I have a program thats using Runtime.exec to execute some external programs sequence with some redirection operators.
    For e.g, I have some command as follows;
    1 - C:\bin\IBRSD.exe IBRSD -s
    2 - C:\bin\mcstat -n @punduk444:5000#mc -l c:\ | grep -i running | grep -v grep |wc -l
    3 - ping punduk444 | grep "100%" | wc -l
    ...etc.
    These command in sequence for a single run. The test program makes multiple such runs. So my problem is sometimes the runtime.exec() fails to execute some of the commands above (typically the 2nd one). The waitFor() returns error code (-1). That is if I loop these commands for say 30 runs then in some 1~4 runs the 2nd command fails to execute and return -1 error code.
    Can some one help me out to as why this is happening? Any help is appreciated
    Thanks,
    ~jaideep
    Herer is the code snippet;
    Runtime runtime = Runtime.getRuntime();
    //create process object to handle result
    Process process = null;
    commandToRun = "cmd /c " + command;
    process = runtime.exec( commandToRun );
    CommandOutputReader cmdError = new CommandOutputReader(process.getErrorStream());
    CommandOutputReader cmdOutput = new CommandOutputReader(process.getInputStream());
    cmdError.start();
    cmdOutput.start();
    CheckProcess chkProcess = new CheckProcess(process);
    chkProcess.start();
    int retValue = process.waitFor();
    if(retValue != 0)
    return -1;
    output = cmdOutput.getOutputData();
    cmdError = null;
    cmdOutput = null;
    chkProcess = null;
    /*******************************supporting CommandOutputReader class *********************************/
    public class CommandOutputReader extends Thread
    private transient InputStream inputStream; //to get output of any command
    private transient String output; //output will store command output
    protected boolean isDone;
    public CommandOutputReader()
    super();
    output = "";
    this.inputStream = null;
    public CommandOutputReader(InputStream stream)
    super();
    output = "";
    this.inputStream = stream;
    public void setStream(InputStream stream)
    this.inputStream = stream;
    public String getOutputData()
    return output;
    public void run()
    if(inputStream != null)
    final BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 128);
    String line = null;
    try
    while ( (line = bufferReader.readLine()) != null)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.DEBUG,line);
    //output += line + System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
    output += line + "\r\n";
    System.out.println("<< "+ this.getId() + " >>" + output );
    System.out.println("<< "+ this.getId() + " >>" + "closed the i/p stream...");
    inputStream.close();
    bufferReader.close();
    catch (IOException objIOException)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("io_exeception_reading_cmd_output")+
    objIOException.getMessage());
    output = ResourceString.getString("io_exeception_reading_cmd_output");
    else
    output = "io exeception reading cmd output";
    finally {
    isDone = true;
    public boolean isDone() {
    return isDone;
    /*******************************supporting CommandOutputReader class *********************************/
    /*******************************supporting process controller class *********************************/
    public class CheckProcess extends Thread
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;
    public CheckProcess(Process monitoredProcess)
    super();
    this.monitoredProcess = monitoredProcess;
    continueLoop =true;
    public void setMaxWait(final long max)
    this.maxWait = max;
    public void stopProcess()
    continueLoop=false;
    public void run()
    //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
    final long start1 = System.currentTimeMillis();
    while (true && continueLoop)
    // after maxWait millis, stops monitoredProcess and return
    if (System.currentTimeMillis() - start1 > maxWait)
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    return;
    try
    sleep(1000);
    catch (InterruptedException e)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    System.out.println(ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    else
    System.out.println("Exception in sleep" + e.getLocalizedMessage());
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    /*******************************supporting process controller class *********************************/

    Hi,
    Infact the command passed to the exec() is in the form of a batch file, which contains on of these commands. I can not put all commands in one batch file due to inherent nature of the program.
    But my main concern was that, why would it behave like this. If I run the same command for 30 times 1~3 times the same command can not be executed (returns with error code 1, on wiun2k pro) and rest times it works perfectly fine.
    Do you see any abnormality in the code.
    I ahve used the same sequence of code as in the article suggested by
    "masijade". i.e having threads to monitor the process and other threads to read and empty out the input and error streams so that the buffer does not get full.
    But I see here the problem is not of process getting hanged, I sense this because my waitFor() returns with error code as 1, had the process hanged it would not have returned , am I making sense?
    Regards,
    ~jaideep

  • Runtime.exec() works in Win98 but not in XP?

    Hi all!
    I have the following problem: I am using following lines of code in win98 to launch a MSDOS-window from my application (with some arguments to it):
    try {
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
    +getArgument(directory,false)
    +"\""+" "+getNoExtent(file));
    proc.waitFor();
    catch (Exception ex) {
    ex.printStackTrace();
    This works very well, however in XP it doesnt do a thing (I know that I have to change 'command.com' to 'cmd' or 'cmd.exe'). I have already tried that but it wont work. Instead, this exception occurs while running on XP:
    java.io.IOException: CreateProcess: start cmd error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    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 JSEdit.actionPerformed(JSEdit.java:443)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1
    113)
    at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mouseRelease
    d(BasicMenuItemUI.java:943)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    What should I do?
    Thanx!
    Regards
    Veroslav

    Check you string concatenation, you're missing spaces or you are not providing the actual code:
    Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
    +getArgument(directory,false)
    +"\""+" "+getNoExtent(file));Let's dissect:
    String command = "start ";
    // command := "start "
    command += "command.com";
    // command := "start command.com"
    command += "/k"+"java -cp \""
    // command := "start command.com/kjava -cp\""You can always trace these kind of errors by using a debugger. Or dump the string you are passing to System.out. Every comprehensive IDE has a debugger built in, or you can resort to jdb.
    Greets
    Dhek Bhun.

Maybe you are looking for

  • How to get a title view at run time

    I want to insert a title for a report which shows title "The Monitor name selected is ------" and whatever selected in the prompt should be displayed along with the static title... I have done with formula @{parameter} and iam getting the desired res

  • ITunes 9 has corrupted my iPod Classic

    So here is my sorry story - please let me know if you have had similar symptoms and if you have found a solution. I have a MacBook Pro, running Snow Leopard. I recently upgraded iTunes to iTunes version 9.0.2 and attempted to synchronise my iPod Clas

  • How Do I Watch Movies (Stored On iPod) On My TV?

    I have a movie on my iPod that I want to watch on my TV. What do I need to do? Do I need a special wire? If so, where do I plug it into the iPod and where do I plug it into my TV?

  • Import and Export Function

    Hi all, My application does not work properly after I do the export/import application function. When I import the application, two things fail - the page authorization scheme and the breadcrumbs. What can i do to avoid this problem ? jeff.

  • What is this border?

    I am working using a Pages template and I want to make it a legal size document, instead of letter size, but when I change the page size, this border does not change. I have included a link to a picture, what is this border? I have looked everywhere