StdIn, stdOut, stdErr for Runtime.exec()

I have searched through 100s of forum messages regarding this topic, but none have helped me enough.
I have an application, app_A, that allows the user to select a database and other environment settings and then run an application using the selected settings. Running app_A on Windows 2000 using a Shortcut with the command: java.exe app_A automatically opens a dos window to write stdOut and stdErr (this is good). From within app_A I do the following:
Runtime rt = Runtime.getRuntime();
rt.exec("java.exp app_B");
app_B, starts up just fine, except that I do not see the stdOut or stdErr from app_B.
Questions:
1. Where is it going and how can I get it?
2. Is there way app_B can have it's own stdOut & stdErr, so the dos window for app_A can be suppressed (it is not really needed)?
many thanks for help and direction
Brent

http://www.apl.jhu.edu/~hall/CWP-Sources/CWP-Examples/Chapter8/Exec/Exec.html may be this class of Marty Hall can be usefull for you.

Similar Messages

  • Feature Request: stdin/stdout/stderr redirection

    I know that CLibInit.setSprite() can setup a text area for
    this purpose - I haven't gotten this to work at all since I've been
    using gluegen wrappers and you need to call setSprite() before
    init() and the glugen wrappers do init() when the static class is
    loaded. Being able to call setSprite() at any time would be a boon.
    But even if I get setSprite() to work, I'd like to be able to
    redirect stdin/stdout/stderr to use some buffers that I can control
    the use of.
    Need to play with file access but something similar would be
    nice there too - controlling file handles to go to buffers under my
    control.

    Lexion wrote:[...]
    int redirect_io()
    freopen(in, "r", stdin);
    return 0;
    int shell_write(char *s)
    // write command to stdin file
    fprintf(stdin, "%s\n", s);
    return 0;
    I don't think its related, but you are writting to a file opened for reading. I believe bash is exiting because after reading the ls command there's nothing left in the file and it gets an EOF.
    You should be using pipes here:
    int fork_shell()
    /* call pipe(), it will give you two file descriptors,
    * one for each end of the pipe.
    // fork another thread to run shell
    shell_pid = fork();
    if (shell_pid == 0)
    /* close the write end */
    /* reassing stdin to the read end, using dup() i think */
    /* reopen stdout to a file (or the write end of another pipe
    * if you want the output to go back to the parent process)
    char *cmd[] = {"/bin/bash", NULL};
    execv(cmd[0], cmd);
    _exit(0);
    /* you may reassing stdout to the write end of the pipe or use it
    * explicitly when sending commands to bash
    return 0;
    Last edited by diegonc (2010-07-28 14:24:02)

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

  • Setting up for Ant 1.6 with Weblogic 8.1 for Runtime.exec()

    Hello all,
    I'm trying to invoke my Ant script using Runtime.exec() but I run into the following exception:
    java.lang.InstantiationException
    Here's my script:
    set ANT_HOME=c:\apache-ant-1.6.1
    %ANT_HOME%\bin\ant %1 %2 %3 %4 %5 %6 %7
    My line of code in Java is the following:
    Runtime.getRuntime().exec("cmd /C build.cmd");
    When I modified my ant script to check the version of ant, I saw it was 1.5.3, not 1.6. I need 1.6 because I'm using certain 1.6 specific ant tasks in my build.xml.
    Does anyone have any idea?

    use WLS 8.1 SP3

  • HELP needed for Runtime.exec

    Here is the code. I'm able to compile it but the code doesn't FTP the file.
    String xfer = "g:/java/code/xfer.txt";
    String xferout="g:/java/code/xferout.txt";
    String[] ftpCommand={"ftp"," -n"," -s:" + xfer + " >" + xferout};
    Process processOutput = null;
    //String homeDir="c:/java";
    //File xferScript=new File(homeDir,xfer);
    PrintWriter xferScript=new PrintWriter(
    new BufferedWriter(
    new FileWriter(xfer)));
    xferScript.println("open " + downloadServer);
    xferScript.println("user " + loginId + " " + password);
    //xferScript.println("lcd " + homeDir);
    xferScript.println("prompt");
    xferScript.println("ascii");
    xferScript.println(method_mget + " " + FileToDownload);
    xferScript.println("dir");
    xferScript.println("bye");
    xferScript.flush();
    xferScript.close();
    Runtime process = Runtime.getRuntime();
    processOutput = process.exec(ftpCommand);

    This should fix it:     String xfer = "g:/java/code/xfer.txt";
         String xferout="g:/java/code/xferout.txt";
         String[] ftpCommand={"ftp"," -n"," -s:" + xfer);
         Process processOutput = null;
         PrintWriter xferScript=new PrintWriter(
              new BufferedWriter(
              new FileWriter(xfer)));
         xferScript.println("open " + downloadServer);
         xferScript.println(loginId);
         xferScript.println(password);          
         xferScript.println("prompt");
         xferScript.println("ascii");
         xferScript.println(method_mget + " " + FileToDownload+" "+xferout);
         xferScript.println("dir");
         xferScript.println("bye");
         xferScript.flush();
         xferScript.close();
         try {
              Runtime process = Runtime.getRuntime();
              processOutput = process.exec(ftpCommand);      
         catch (IOException ioe) {
              System.out.println("I/O error has occurred");
         ioe.printStackTrace();
         }Mark

  • Stdout/stderr for NT service using com.ms.service

    Hi,
    I have a Windows NT service created using com.ms.service
    I was wondering where are System.out and System.err pointed.
    Searched for "log", "out", "err" files with the name of service but nothing found. Also searched for services.log etc.
    TIA

    Here is another tool that enables you to run Java applications as Windows services: http://www.alexandriasc.com/software/JavaService/index.html
    Jesper

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    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 Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 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.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • Runtime.exec() output streams

    Hi,
    I am using Runtime.exec() to execute a whole slew of commands - running batch files and executables. It is really important that I can see the output of my programs, and the fact that Runtime.exec() doesn't spawn its own Command-Prompts is a little disconcerting. In order to get around this, I am handling the stdout and stderr output streams from the processes synchronously with threads (as detailed in the Java Pitfall article - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html). I call Runtime.exec(command[], env[], dir) where command contains "cmd.exe" "\C" command.
    My question is, if one of my processes crashes, will my threads receive ALL of the output from stdout and stderr just as a Command-Prompt would? If not, what is the workaround? Using Psexec to run the processes seems to bring up the Command-Prompts like I would like it to, but that doesn't always behave the way it should be, so I cannot rely on that just to see the command prompts.
    I don't want to have to switch to C# or C++ to do this at this point, but if there's no real answer, it looks like I might have to.

    cotton.m wrote:
    munky135 wrote:
    Hi,
    I am using Runtime.exec() to execute a whole slew of commands - running batch files and executables. It is really important that I can see the output of my programs, and the fact that Runtime.exec() doesn't spawn its own Command-Prompts is a little disconcerting.Hilarious. Oh. You were being serious there were you? :|Yes, I was being serious. I call runtime exec and I am not getting Command-Prompts to pop up, their output is being piped to my Java application. Reading directly from the API:
    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 Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 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.
    >
    I don't want to have to switch to C# or C++ to do this at this point, but if there's no real answer, it looks like I might have to.Based on your attitude you should switch. You obviously hate Java and are ready to see faults that don't exist based on misconceptions that you hold. Fine, to each their own. Choose a language you like then. Which at a guess I would say is likely VB.Huh? I love Java. Any misconceptions I hold are from this guys article here - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Backgrounding Runtime.exec

    Is there a way to background a Runtime.exec() call to a batch file? What I want to do is right after the batch file is executed I want to exit java and keep the .bat process running in the background. I am creating a process that lets the user upgrade a local JVM in the directory. But you can't necessarily do that from java. So I have a .bat file that extracts the necessary files. Any suggestions on how to background that?

    Hmmm as far as i know the Process created by Runtime.getRuntime.exec(String ex), runs independantly of the creator. And that is also what i get from reading the Process API, espacially this part "The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously":
    API BEGIN
    The Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.
    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 Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. 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.
    The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.
    There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object.
    API END
    Poul Krogh

  • Runtime.exec(command)

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

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

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

  • Runtime.exec() fails to run "javac" with "*.java" as arguments

    Hello,
    I am observing that Runtime.exec() consistently fails to execute "javac" when the Java files to be compiled are specified as "*.java". It fails with the following error:
    javac: file not found: /home/engine931/*.java
    Usage: javac <options> <source files>
    The same command used for Runtime.exec() runs fine from a the command shell. Is this is known problem with the Runtime class on UNIX, because it works fine on Windows.
    Any advise is appreciated.
    Thanks,
    Ranjit

    Your shell is expanding the command when you run javac from the shell. Try constructing your Runtime parameters so that your shell is executed, which then executes javac.
    The specific behavior is entirely dependent on the command interpreter that's used.

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • [advanced] Runtime.exec() and ordering of stdout, stderr

    Hi,
    When invoking Runtime.exec(), I'd like to output the contents of stdout, stderr in the correct order. I am using Process.getInputStream(), Process.getErrorStream() and output those but I can't get the order right.
    For example, the following events occur:
    1) stdout: "c:\> dirt"
    2) stderr: "dirt is a bad command or filename"
    3) stdout: "c:\>"
    When I run my program I get the following output:
    c:\> dirt
    c:\>
    dirt is a bad command or filename
    My output has #1 and #3 merged and #2 in its own. The placement of stderr is crucial in my program; how can I possibly synchronize the two streams and know which text goes where?
    Please help.
    Gili

    Crosspost. See Advanced forum.

  • 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

Maybe you are looking for