Runtime.exec has taken my sanity.

I have been battling this command. All I get is "exit value: 1" using the "when runtime exec wont" code.
I've gotten to the point where I only see red. What am I doing wrong?
          String[] cmd = {
               "c:\\program files\\lynx\\lynx.exe",
               "-cfg=c:\\program files\\lynx\\lynx.cfg",
               "-lss=c:\\program files\\lynx\\lynx.lss",
               "-dump " + webpage,
               "> " + filename};
      Process proc = rt.exec(cmd);

The redirection operator '>' has to be interpreted by a command processor. You are not using one. I would expect to see something like
String[] cmd = { "cmd.exe",
                        "/C",
               "\"c:\\program files\\lynx\\lynx.exe\" \"-cfg=c:\\program files\\lynx\\lynx.cfg\" \"-lss=c:\\program files\\lynx\\lynx.lss\" -dump \"" + webpage + "\" > \"" + filename +"\""};The quotes round the argument are needed because the file names contain spaces. Very messy. :-) You need to check that I have got that bit right - I hate checking quotes.
P.S. I assume you have read, digested and implemented the recommendations in the 4 sections of [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] .

Similar Messages

  • Use of Runtime.exec

    I know that there are security concerns with making a call to the java.lang.Runtime's
    exec method, but are there any performance concerns? When an exec call is made
    by an object within the application server does the forking of a new process to
    execute the command cause a process equivalent in size to the application server
    to be generated? Our application server process is quite large, so this would
    be an expensive operation.

    The OS-level semantics of Runtime.exec are tied to JVM implementation (that's why
    it doesn't work on most releases of the MacOS for example)...
    Runtime.exec has a lot of not-so-intuitive handholding associated with it. For
    example, did you know that on most flavors of Windows JVMs, you have to read out
    of the STDOUT and STDERR streams, or the process you invoked will hang when their
    buffer fills up? JavaWorld ran an article a while back with all the details on
    this-- you can write a stream gobbler to suck up anything and send it to /dev/null
    to avoid problems.
    "Ash Beitz" <[email protected]> wrote:
    >
    I know that there are security concerns with making a call to the java.lang.Runtime's
    exec method, but are there any performance concerns? When an exec call
    is made
    by an object within the application server does the forking of a new
    process to
    execute the command cause a process equivalent in size to the application
    server
    to be generated? Our application server process is quite large, so this
    would
    be an expensive operation.

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

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         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);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Runtime.exec error - java.lang.NullPointerException

    Hi,
    I am trying out the example code from javaWorld that shows how to use exec to execute external command. The problem is that I aways run into java.lang.NullPointerException on line that has "Process proc = rt.exec(cmd);" I have tried to run the code under Windows XP and Windows 2003; and I get the same error message. Any idea on what might be casing this?
    Thanks,
    // GoodWindowsExec.java
    import java.util.*;
    import java.io.*;
    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();
    public class GoodWindowsExec
    public static void main(String args[])
    if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    String[] cmd = new String[3];
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    else if( osName.equals( "Windows 95" ) )
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process 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();
    }

    What is System.getProperty("os.name") returning when you run on Windows XP or 2003?
    You are only filling in your cmd array when os.name is either Windows NT or Windows 95. In other cases, the elements of cmd are left as null.
    The documentation for Runtime.exec() says you will get a NullPointerException when elements of the array are null:
    http://apidoc.org/view/10563?a=exec%28java.lang.String%5B%5D%29

  • Parameter  to shell script using Runtime.exec(string)

    Hi all, ( Speciall hi to dheeraj tak )
    Briefly : How do i pass an arguement to a non - java executible being called using Runtime.exec.
    In detail : i am using Runtime.exec to call a shell script : The code is as follows:
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh"};
    try {
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    This works properly & calls the shell script which in turn invokes some other executible (c file).
    $HOME/midi/test/build/bin/<C-EXECUTIBLE>
    Here i am specifying the name (say hello.exe ) . So far so good.
    I want to make this happen dynamiclaly. so i need to pass the name of the executible as a parameter to the script.
    To pass a parameter i hav to change the string to :-
    String callAndArgs[] = {"/home/tom/jakarta-tomcat-4.1.24/webapps/dash/script.sh <C-EXECUTIBLE HERE>"};
    and the script to
    $HOME/midi/test/build/bin/$1 --- where $1 refers to argument 1. (C-EXECUTIBLE AGAIN).
    This is giving an IO - Execption. Plz help
    Code will be very helpful.
    Thanx in advance

    some 1 plz tell me the difference :-
    This is the documentation of Runtime.exec that i found :-
    1> exec
    public Process exec(String command) throws IOException
    Executes the specified string command in a separate process.
    The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).
    Parameters:
    command - a specified system command
    Complete refernce says : Process (String progName) ----- Executes a program specified by programname as a seperate process.
    2> exec
    public Process exec(String cmdarray[]) throws IOException
    Executes the specified command and arguments in a separate process.
    The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).
    Parameters:
    cmdarray - array containing the command to call and its arguments.
    Complete reference says : Process exec(String comLineArray[]) ---- Executes the command line specified bythe string in comLineArray as a seperate process.
    This means that there is provision 4 command line arguments...
    how do u use it then????????????????????????????

  • Runtime.exec not releasing lock on files

    Hi,
    I am using Runtime.exec to launch an external application, a batch file that runs a java program and generates a pdf file on disk. The Runtime.exec is called from inside the callback function of a toolbar button in my UI. Once, the runtime.exec returns, I popup a alert saying "pdf generated successfully". However, when I try to open the pdf that has been generated, I get a message saying the "program is in use by another program" or some such message. Only when I quit my GUI application, Iam able to open the pdf file using acrobat reader.
    Can someone tell me how to solve this problem. I have tried doing proc.waitFor() etc.
    Cheers,
    vidyut

    You can try some of sysinternals tools to look through file sharing information and decide what process is locked file.
    PS Try to ensure that you start java in same process as batch file executes, overthise you just can't ensure it terminates on time.

  • Using Runtime.exec on a Unix System

    hi,
    I have a web service which executes a command line process 'Runtime.exec(command)'. When the server starts to go on a high load I start to get "IOException: Not Enough Space" which I understand means that I am running out of swap space. No problem as I can increase the swap space to cope with demand. The problem is that I have read that when JVM attempts a fork on a Unix system it temporarily creates a new JVM with the same space requirements as the app server JVM. So if I set my app server to require 1GB memory, I am likely to need to set up swap so that it has 1GB * Number of Parallel Processes. I need to know if this is correct. Our application today does not limit the number of Runtime.exec commands which can be run in parallel and if the above is true we are going to have a problem ensuring we don't run out of memory.
    Can any one verify this or suggest other solutions to the problem?
    Thanks
    Stephen

    hi,
    Yes, very helpful jwenting! Problem is that we are working with legacy systems where we have few other options. If you can give any positive input it's not worth leaving your option at all.
    Thanks
    Stephen

  • Java's Runtime.exec() method

    When you shell out to java's Runtime.exec() method, are the process name and arguments the same for the child process that is spawned.
    We see duplicated processes about the time when our logs tell us this command was run. However, we cannot seem to reproduce this. Has anyone else seen anyone this before?

    That's what I though too. But check this out . . .
    Our code looks as follows:
    private Runtime rt;
    private Process p;
    rt = Rutime.getRuntime();
    p = rt.exec(command);
    This exec() call creates a new process, which is a child of the java process that runs this command. The final process looks like the "command" string that is passed to the exec() method call. In our case, the command is a call to the /usr/bin/mail utility to send out faxes and emails.
    We ran a very tight loop executing the rt.exec() call over and over. What we found was that for a minor fraction of a second, the newly created process looks just like the original process including the same arguments. However, the PID's indicated that one process was the child of the other. This is why it looked like we had 2 of the same processes. WILD!
    Thanks guys!

  • Using Runtime.exec to execute a C++ executable

    Hello,
    I would like to know if it possible to execute a C++ executable using Runtime.exec() and wait for it to complete and how do I read back the output file created by the C++ executable into the Java Code?
    TIA.
    RHP

    When I execute the code with Runtime.exec(), and read
    from the Process's inputStream I am ablt to view the
    cout from the C++ code. But the output file that has
    to be created by the C++ code is not created,Then this is maybe an error in the C++ code? Maybe you don't have permissions to create that file where you want to.
    where
    would the output from the C++ code go to when I use a
    ofstream in my C++ code andIf you create the file stream in C++ with an absolute file name then the output goes into that file. If it's a relative file name, then the basis is most likely the current working directory (found in the system property "user.dir" if you used one of Runtime's methods without the File argument, otherwise it's the directory you provide.
    How do I read both streams
    from the Java Code?You create an FileInputStream and - if you want to read character instead of binary data - on top of that an InputStreamReader. You might add a BufferedReader on top of that if you want to read line by line.
    does that answer your questions?
    robert

  • Runtime.exec()  in Java not working in Oracle 10 Application Server

    Hi ,
    I am trying to call a .exe file which is in the Web Application folder .
    I am Using Process p = Runtime.exec("path to .exe file ")
    This code is working fine when used with JBOSS , but not working with Oracle Application server .
    Please tell me whether i need to do any chnages to make it work
    Thanks in advance .

    I ran a quick test with your code, I just had to make some small changes, and things work for me...
    I'm testing with JDeveloper 10g 10.1.3.2.0 ...
    The only thing I wonder is DBUser DBPass DBHost, those are not the actual values, correct?, neither they are environment variables?...
    In the server hosting your OAS, you should try running the whole CMD line from the start/run dialog ... make sure it works in that server ...
    Here is the code used in my test:
    In JSP:
      <%@ page import="runexepkg.*" %>
      <% 
      String msg = "";
      try
      RunEXE p = new RunEXE();
      msg = p.main1();
      catch(Throwable t)
         System.out.println("Exception Raised");
         t.printStackTrace();
      %>
      <%= msg %>In Java Class:
    package runexepkg;
    import java.sql.*;
    public class RunEXE
        String ss="";
        public String main1()
        try
            Runtime rt=Runtime.getRuntime();
            Process p = rt.exec("CMD /C start C:\\oraappserver\\j2ee\\WebGis\\applications\\PowerGis\\web\\WEB-INF\\classes\\GisProject\\cust_data_1.exe DBUser DBPass DBHost");
            System.out.println("Command has been executed");
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@DBHost:DBPort:orcl","DBUser","DBPass");
            System.out.println("Test Connection ========== "+con);
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("SELECT SYSDATE FROM DUAL");
            if(rs.next())
                ss="Command has been executed - Database has been accessed";
            else
                ss="Command has been executed - Database was not accessed";
        catch(Throwable t)
            System.out.println("Exception raised, command has NOT been executed");
            ss="Exception raised, command has NOT been executed";
            t.printStackTrace();
        return ss;
    }Edited by: Rodolfo Ferrari on Jul 23, 2009 10:40 PM

  • Runtime.exec not executing the command !

    Hi all,
    I'm connecting to Progress Db thru JDBC trying to execute a stored procedure
    which has a statement
    Runtime.exec("ksh -c aa") where aa is aunix script which i'm trying to run from java snippet .
    when i run this code as a seperate java program it executes the script
    "aa" but thru JDBC connection it does not execute the command
    what could be the reason ???
    thanx in advance,
    Nagu.

    Hi Rick,
    "aa" is the shell script which is lying in the user DIR .
    It is returning a non-zero value. what kind of permissions be there for to execute the Shell command?
    Regards,
    Nagarathna.

  • Set Path to DLLs for Runtime.exec(...)

    I have got a little server application that creates a Process of an external application. (eg Example1.exe or Example2.exe - which one is to be called is configurable via property files)
    All of these external apps rely on a couple of DLLs, that are distributed seperately from the ExampleX.exe.
    So my directory structure looks something like this:
    /Server (contains my java app)
    /Server/dll (contains the dlls)
    /Server/app (contains ExampleX.exe files)
    How do I configure my Runtime.exec(...) so that it can supply a PATH info to my DLLs?
    How about the ...exec(String command, String[] envp, File dir) call?
    -> It already works when the DLLs are in the same dir as my .exe files.
    -> I would like to avoid setting a global PATH to my DLLs in the OS.
    Has anybody already dug itself through this pile?

    Solved my problem, awarded the Dukes to myself! ;-)
    Here's what I did in case somebody else has similar probs:
    The envp Parameter didn't work for me. The Application and the DLLs were found but the Subprocess was somehow screwed up - the Threading didn't work right. (I have no clue how that could be, but whatever...)
    Anyway I could put the path to the DLLs in the PATH info of my startup script for the Java-Server. The subprocess inherits that information.
    I used relative path info there so that nobody has to fiddle around in the script when the application is moved to different directories.
    The only thing you have to do then is to set the present working directory of the subprocess to the location of the server via ...execute(String, String[], File)
    You need to supply thecomplete path to the application in the first String parameter that way but all in all this semms to be the most sensible way to do it.

  • Runtime.exec() hangs with 1.4.1

    Hello altogether,
    I am trying to execute a command with Runtime.getRuntime.exec()
    I have already taken care of capturing the output and I observe that depending of the program I try to execute the process hangs.
    I am using JRE 1.4.1_02 under Redhat 7.2 with kernel 2.4.18-26
    Executing the same program under JRE 1.3.1 the program does not hang.
    Executing 'top -bn0q' hangs, executing 'ls -als' it hangs.
    Here is my sample code:
    <code>
    import java.io.*;
    public class Exec
    /** catches the output in a parallel thread */
    class StreamReader extends Thread
    String category = null;
    InputStream is;
    StreamReader(String category, InputStream is)
    this.category = category;
    this.is = is;
    public void run()
    try
    System.out.println(this.category+": reader runs");
    InputStreamReader isr = new InputStreamReader(this.is);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while (br.ready() && (line = br.readLine())!=null)
    System.out.println(this.category+':'+line);
    catch (Exception e)
    e.printStackTrace();
    public void run(String[] cmd)
    StringBuffer outStrBuf = new StringBuffer();
    try
    Runtime rt = Runtime.getRuntime();
    System.out.println("got runtime");
    Process process = rt.exec(cmd);
    System.out.println("fired cmd");
    // any errors
    System.out.println("prepare error stream");
    StreamReader errSr = new StreamReader("ERR",process.getErrorStream());
    // any output
    System.out.println("prepare output stream");
    StreamReader outSr = new StreamReader("OUT",process.getInputStream());
    // start the readers to read
    System.out.println("start readers");
    errSr.start();
    outSr.start();
    System.out.println("waiting for process to end");
    process.waitFor(); //Waits for the subprocess to complete.
    catch (Exception e)
    System.err.println("Error while executing cmd: " + cmd);
    e.printStackTrace();
    System.out.println(outStrBuf);
         public static void main(String[] args)
    String [] cmd = {"top","-bn0q"};
    if (args.length >= 1)
    cmd = args;
    System.out.println(args[0]);
    Exec exec = new Exec();
    exec.run(cmd);
    </code>
    The output of java Exec is:
    [user]$ java Exec
    got runtime
    fired cmd
    prepare error stream
    prepare output stream
    start readers
    waiting for process to end
    OUT: reader runs
    ERR: reader runs
    ...and there it hangs. Interesting is, that when I use ls -als as command, I get the directory listing.
    Do you have any ideas what I am doing wrong? Is there any difference in the Runtime.exec() between 1.3 and 1.4 version?

    Unbelievable and what a shame. I was hacking 2 days on several variations of this problem and the solution and I finally found one difference:
    while (br.ready() && (line = br.readLine())!=null)
    I assume that when executing the command, the output streams are not ready and my Output gobbler threads end.
    ...however the command is still executing and starts to write its output. And as we all know this will overflow the buffer and the process hangs.
    So the final solution is:
    /** catches the output in a parallel thread */
    class StreamReader extends Thread
      String category = null;
      InputStream is;
      StreamReader(String category, InputStream is)
        this.category = category;
        this.is = is;
      public void run()
        try
          System.out.println(this.category+": reader runs");
          InputStreamReader isr = new InputStreamReader(this.is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while (/**br.ready() &&*/ (line = br.readLine())!=null)
            System.out.println(this.category+':'+line);
        catch (Exception e)
          e.printStackTrace();
    }So the only question that I have open: Why does this makes no problem with 1.3 but with 1.4 ?

  • Runtime.exec error in windows

    When i try to run an external program with Runtime.exec() in windows 2000, i get a windows pop-up with the following error msg:
    d:\winnt\system32\ntvdm.exe
    Error while setting up environment for the application.
    I have no idea how to fix this since i have no clue to what that error means.
    Thanks
    Rumy

    I've personally just encountered the same error. I am building a piece of demonstration software to distribute with my graduate school applications to demonstrate my programming experience and I wish to include a set of programs I wrote some years ago in Pascal and C++. The software has been compiled for MS-DOS 6.0. I am using the following command to execute the software from within my Java program:
    Runtime.getRuntime().exec(new String[]{"command.com","/c","12cards.bat"});The batch file performs the appropriate setup operations for the program and runs the executable. When I run this code segment, I receive the following error:
    [16 bit MS-DOS Subsystem]
    C:\WINNT\system32\ntvdm.exe
    Error while setting up environment for the application. Choose 'Close' to terminate the application.
    I have another code segment in which I attempt to run the executable myself (without the help of command.com or the batch file). The code segment is as follows:
    Runtime.getRuntime().exec(new String[]{"12cards.exe"}, new String[0], workingDir);When I run this code segment, the following IOException is thrown:
    java.io.IOException: CreateProcess: 12CARDS.EXE 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 (my code)I have already found the document on Microsoft's support website which describes a solution to this problem. Manually extracting the autoexec.nt, config.nt, and command.com files from the installation CD-ROM did not help.
    The most confusing element of this: 12CARDS.EXE runs fine if I execute it from Windows Explorer. It's only a problem if it's executed from within my Java program. I have two other DOS programs which I want to include as well; I am having the same trouble with them.
    Any advice will be much appreciated. Thanks!

Maybe you are looking for

  • Macfixit Guide to Installing an Upgrade like 10.4.8

    http://macfixit.com/ Update procedure recommendation We recommend the following procedure when installing Mac OS X 10.4.8. First, avoid performing any other operations (in Mac OS X or third-party applications) while the update process is occurring. I

  • Unable to call HttpSevlet from java web server

    Hi , I have followed the tutorial given in jdeveloper,creating a Httpservlet. I followed the steps and tried calling the sevlet. I got 404 error. Can any one clarify how to view the web page outside Jdeveloper and how to configure JavaWebServer.

  • How do i fix a home button that keeps pressing itself

    My home button keeps pressing itself at random times without me even touching or holding the device. When I press the home button itself once in awhile it works, most of the time it doesn't. I've already done all the possible quick fixes suggested on

  • Fixed substitution into PCA (ledger 8A)

    Hi, I want to achieve a fixed substitution into the fixed ledger PCA, *A. When posting from an FI journal I want the transaction type field to filled filled with a constant value liek 'XXX'. I tired using the fixed field movement (GCI4) but did not s

  • Document from file - how better store information about document?

    I have a text file that contains information about documents (content from groups than define the document - one row is one document). Every group content from fields (from 10 to 70 in every group). Document consist of 9 groups. In one documen can di