Runtime.exec() and subprocesses

I am running a bat file through Runtime.exec(). Conetent of bat file look
likes following
E:\Progra~1\Brio\SQRServer\ORA\BINW\sqrw d:/brio/par/par_pqa.sqr
ibprod/active1@pscore -oC:/TEMP/sqr.log -printer:pd 88
d:/Brio_Reports/report1.pdf d:/brio/
exit
Now this batch file starts another executable program. That program creates
a report in a particular directory and exit the process. When I run this
file from command prompt it runs fine. But if I try same thing from
Runtime.exec(), my program hangs.
From windows process monitor tools it seems that it start a new process but
that process never ends. If I end that process forcefully then pointer
again returns to my java program.
any idea how to solve this problem.

Is there maybe any stdout or stderr (console so to say) output which is not taken care of when the thing is called from Java?

Similar Messages

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

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

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

  • Runtime Exec and ProcessBuilder

    I have an object (textTicket) which is a formatted transaction label. Here is an example:
    CROSS PLAINS QUARRY CROSS PLAINS TN 37049 2549
    MATL SPREADING NOT GUARANTEED
    615-654-9942 TOLL FREE 877-654-9942
    Date: 01/19/2009 04:45:46
    Job No: PU-2008
    Q Num::
    Cust No: 30000001 Src Num::
    Sold To: CASH SALE
    Address: INTERNAL
    NASHVILLE,TN 37202
    Ord By:
    Ord No: Rate Zone:
    Location:THANKS YOU
    Mat. & Haul170.28 Sev Tax:0 Tax16.60
    Acc Total:1308.16
    Total186.88
    3/4 TO 4/67'S
    Gross: 40500 St. Item:
    Tare: 12120 P.O.: MIKE MILLER
    Net: 28380.0
    Net Tons: 14.19
    Proj:
    Truck #: 1
    Hauler: Phy Truck: 248251
    I am attempting to pass this textTicket object to a shell script that will send it out the port for printing. I have tried using the Java Comm API however, we have intermittent problems with the API running on an Oracle Appserver. Sometimes, the data never gets sent to the port. So what I am trying to do is just call a shell script that echos the textTicket out the port via redirection. The problem arise when I use the ProcessBuilder or runtime exec and I have to convert the textTicket to a string via textTicket.toString. The textTicket then losing all of its formatting. Any ideas on how to keep the formatting as I am passing the textTicket to the shell script.

    My example did not save into the post very well. For instance, the first line "Cross Plains Quarry" should be center on the paper. The object contains \t\t to get it center.
    For example on the runtime.exec, I am doing the following
    public void printShell(String port, String string){
         String[] params={"/usr/ts/bin/prttick.sh", string, port};
         try {
                   Process p=Runtime.getRuntime().exec(params);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   SerialCommunicator.logger.debug("error" + e.getMessage());
    The variable string is textTicket.toString();

  • Runtime.exec and setting environment variables

    Runtime.exec and setting environment variables
    I need a decent example which works on Windows.
    Got any?

    Thank you.
    I was hoping for an example of the use of
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[]) or
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runti
    e.html#exec(java.lang.String,%20java.lang.String[],%20j
    va.io.File) which take environment variable
    information such as PATH.
    The reason is because there is a library which is
    being loaded via loadLibrary (
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Syste
    .html#loadLibrary(java.lang.String) ). However, for
    the child process to find the library the PATH needs
    to be updated.
    Any example regarding changing the PATH variable via
    Java so that libraries can be loaded and processes
    created? (Perhaps, I should make a new post and
    restate the question with this more explicit
    information?)
    That won't work. LoadLibrary occurs in the JVM environment. As I said you can't change the JVM environment via exec().
    If the shared library needs something in the path then you are going to have to set the path before your application starts up.
    If you just need to load the library from someplace that is not on the path then you should be using System.load().

  • Problems with Runtime.exec() and certain Unix processes

    Certain Unix processes don't behave correctly when run from Java using Runtime.exec(). This can be seen by running /bin/sh and trying to interact with it interactively. The issue appears to be that /bin/sh (and many other Unix tools) are checking the file handles on the spawned process to see if they are associated with a TTY.
    Is there any way to associate a process spawned by Runtime.exec() with a terminal or alternatively, is there a JNI library available that would setup the process correctly and still provide access to the input and output streams?
    Our objective is to have the flexibility of expect in being able to run and interact with spawned processes. A bug was opened at one point but closed back in 1997 as being a fault in the spawned process, not Java.
    Bug ID: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4058689

    #include <stdio.h>
    void doit() {
    int c;
            while((c=getc(stdin)) != EOF) {
                    printf("%c",c);
    int main() {
            freopen("/dev/tty", "r", stdin);
            doit();
    }This program reopens its standard input against /dev/tty and catenates it to stdout. And voila, it takes its standard input from the terminal, even though it was started with stdin against /dev/null..
    $ gcc b.c -o b
    $./b < /dev/null
    buon giorno
    buon giorno

  • Runtime.exec() and white space

    Hello,
    I am attempting to run a DOS -based hydrological modeling from NT using the Runtime.exec() method. When executing the command:
    "Hec1.exe filename"
    the model runs successfully.
    When I try executing the command:
    "Hec1.exe filename > null", the method recognizes the string array as "Hec1.exe filename>null", which causes the model to fail.
    Here is the code that I use to execute the process:
    Runtime rt = Runtime.getRuntime();
    String[] cmd = new String[4];
    cmd[0] = "Hec1.exe";
    cmd[1] = inputFile;
    cmd[2] = ">";
    cmd[3] = "null";
    Process p = rt.exec(cmd);
    Hopefully, there is some sort of workaround that one of you knows.
    Thanks for your time.
    -Joel Finkel

    and yes that batch file is correct but if you want it to be more usefull change that filename to $1 or %1 i forget which(been working in both *NIX and DOS too long)                                                                                                                                                                                                                                                                                                                                       

  • Runtime.exec and ServerSocket for IPC...blocking problems

    I have built an IDE for assembling/deploying web applications.
    I am supporting a 'test' mode in the IDE where a compiled 'solution/application' is executed in a separate vm from the IDE using Runtime.exec. For the whole sandbox thing. Don't want a wayward application crashing my IDE.
    Naturally I want a way to communicate start/stop from the IDE to the running application. So sockets are my only choice. Calling process.destroy from my IDE won't invoke a shutdownhandler in the generated application's vm, and I want an orderly shutdown as the generated applications open resources/etc.
    When I execute the generated application from within the IDE the thread code that creates a server socket blocks in the ServerSocket constructor...why?
    When I execute the solution using 'java' outside of my IDE, I can set up a server socket and all works fine.
    My IDE is NEVER creating server sockets waiting for client connects...only the generated application does this. So it isn't a case of the IDE already listening for requests on the same port as the server/generated application.
    Proving the above is that I can manually start my generated application, start my ide, then invoke the menuitem from the IDE that writes a 'close' byte to the client's socket...and the running application DOES shut down.
    Any ideas?

    I have decided on a different approach.
    At first I thought...ok I have the ServerSocket on the wrong 'side'. I then put the ServerSocket code in the always-running IDE and the Socket code on the running/exec'd application. But still a hang on the running application when constructing the Socket.
    I decided instead to call Process.destroy on the running app.
    Given that generated app is running in a separate vm, when it shuts down via process.destroy from the ide...although vm shutdown hooks aren't called...I guess it's ok since a destroy of the vm will release all resources. Not as clean as I'd like though.
    Additionally, I cannot determine 'true' start of application as no socket notification can be done. I merely determine start after a Runtime.exec of jvm process. Subsequent errors in startup will merely be determined by the IDE in process.waitFor or process.exitValue.
    I was getting a wierd socket error when attempting my prior solutions...and not a lot on the web regarding this subject...all relevant posts seemed to be in German/from Germany. Odd. Would need my wife to translate! Mein gott!
    I guess I could've communicated from ide to Runtime.exec'd application via a generated file in filesystem...but this seemed cheesy. Sockets should've been used for ipc between java vms...or so I thought.

  • Runtime.exec and cmd.exe

    Just a quick one here, I think. I'm working on a little tool to merge changes into a document and then copy it over a communications port, and everything seems to be checking out except for that last step. Rather than worrying about streams and whatnot, I'm saving the file to the hard drive; from here, my plan has been to open the DOS prompt and take advantage of its "copy (filename) (port)" command to transfer the file. So in the end, the key line of Java should be something like
    Runtime.getRuntime().exec("cmd.exe copy \"" + fileName + "\" LPT1");My issue here is that the command prompt doesn't seem to want to open using Runtime.exec(). It seems like cmd.exe should do the job -- tossing that into the run menu certainly opens the prompt -- and even just to be sure, I've tried using C:\WINDOWS\system32\cmd.exe explicitly, and both that at cmd.exe without any additional arguments. Strangely, though, the prompt isn't opening, and I'm not getting an I/O error out of it as if I was sending in a bogus command.
    So what am I doing wrong here? What do I have to do to open the DOS prompt?

    As I mentioned, I did try providing the full path to cmd.exe, to no effect.
    Curiously, though, changing "cmd.exe" into "cmd.exe /k" or "cmd.exe /c" both cuased the command to run correctly. Contrary to what they're supposed to do, though, both of them result in the immediate termination of the DOS prompt, even though /k is supposed to cause the window to persist. Any ideas as far as that one goes?

  • Runtime.exec() and security ?

    Hello,
    I have a program where a user can enter a binary path to openssl. The program then appends some hardcoded arguments to the openssl binary to do some crypto operation. I'm using Runtime.exec(String) to execute the command. For example:
    */usr/bin/openssl* smime -sign -certfile ....
    Only the bold part of the command can be chosen by the user.
    I'm a bit concerned about the security and I'm scared that a user could actually execute any command by injecting some shell code by entering for instance "verybadcommand #". I tried this and the execution fails which is good but are there any special things I should keep on mind ?
    Thanks in advance,
    Tex
    Edited by: Tex-Twil on Feb 25, 2009 8:35 AM

    Solved the problem. I was setting the DISPLAY variable when I launched the X application but not the XAUTHORITY variable. Once that was set the X application launched as expected.
    - Bill

  • Runtime.exec() and fork() and Process

    So let me see if I understand this correctly, and if I don't please fill me in. If I call the following piece of codeRuntime.getRuntime().exec("chgrp rcsweb " + path+fs+orgName);
    Runtime.getRuntime().exec("chmod 660 " + path+fs+orgName);where path is the real path to a file, fs is short for File.spearator and orgName is the name of a file, then in the Unix environment, it will fork off a process.
    First, I seem to remember one forum topic that mentioned not forgetting about killing the process returned by exec, so I guess I need to add that to my code.
    Second, since I am forking off this process inside of a J2EE container, am I actually forming off the entire container, or just the Servlet where Runtime is called, or what?
    Third, how can I prevent the error java.io.IOException: Not enough space
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:54)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:546)
    at java.lang.Runtime.exec(Runtime.java:413)
    at java.lang.Runtime.exec(Runtime.java:356)
    at java.lang.Runtime.exec(Runtime.java:320)when I do not have the option of changing my VM size? Is killing the Process (and using waitFor()) going to take care of this issue?
    I appreciate your help.

    OK, after writing a few test programs, it is indeed clear..on unix (at least on solaris) when calling runtime.exec(..) The ENTIRE VM does indeed get forked. Therefore if your current Memory allocation for you VM is sitting at say 64MB (or you initial memory setting), another 64MB process will be created, even if you doing something as a simple
    exec("ls");
    I also tried putting runtime.exec call in its own thread hoping that if it was not in the main thread, that only that process would be forked..to no avail..the entire vm is indeed forked everytime...making runtime.exec damn near useless for server side work, and very dangerious..as you can essentialy assume you always need 2x your memory requirements.
    If anyone has figured out a workaround...any suggestions greatly appreciated.
    Some thoughts on some work-arounds
    1. Run 2 VMs (then when native calls are required..send a message to the 'native-calling vm' (insure its memory footprint is very low)
    2. Write your exec method via JNI (or does JNI calls also result in a fork of the vm on unix..)
    Test code below (threaded version)
    import java.util.*;
    import java.io.*;
    public class test5 extends Thread
         public void run()
              int loops = 0;
              while (true)
                   loops++;
                   System.out.println("---- iteration " loops "---");
                   makeNativeCall();
         public static void main(String[] args)
              try
                   System.out.println("testing on OS: " + System.getProperty("os.name"));
                   // Allocate a nice chunk of memory
                   byte[] bytes = new byte[1024 * 1000 * 50];
                   test5 tst = new test5();
                   tst.start();
                   while (true)
                        Thread.sleep(1000);
         catch(Exception e)
         {e.printStackTrace();}
    public void makeNativeCall()
              Runtime runtime = Runtime.getRuntime();
    InputStream stderr = null;
    InputStream stdout = null;
              OutputStream stdin = null;
    Process proc = null;
    long totalMem = (long)(runtime.totalMemory()/1024);
    long freeMem = (long)(runtime.freeMemory()/1024);
    long usedMem = (long)((totalMem - freeMem));
    System.out.println("VM REPORT: TOTAL(" totalMem") FREE("+freeMem+") USED(" usedMem")" );
    try
    proc = runtime.exec("sleep 1");
    stderr = proc.getInputStream();
    stdout = proc.getErrorStream();
    stdin = proc.getOutputStream();
    String line = null;
    int i = 0;
    String error = "";
    int exitVal = proc.waitFor();
    if (exitVal != 0)
    System.out.println("ERROR " +exitVal);
    System.out.println("DETIAL" +error);
    catch(Exception e)
    e.printStackTrace();
    finally
    if (stderr != null)
    try{stderr.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdout != null)
    try{stdout.close();}catch(Exception ignore){ignore.printStackTrace();}
                   if (stdin != null)
    try{stdin.close();}catch(Exception ignore){ignore.printStackTrace();}
    if (proc != null)
    try{proc.destroy();}catch(Exception ignore){ignore.printStackTrace();}

  • Runtime.exec() and batch files

    I am having a problem on Windows 2000 while trying to execute a batch file with the Runtime.exec() method. Basically, the exit value returned from the call to Runtime.exec(), returned specifically by the waitFor() method in the Process class, is always zero, even if the batch file fails miserably. After looking into batch files further, it seems to me that the only way to get the exit value of the commands run in the batch file back to the Runtime.exec() call is to put "EXIT %ERRORLEVEL%" in the batch file. What this actually does is exit the command(cmd) shell that the batch file was running in with the exit code of the last command run. This is all great when calling the batch file with a Runtime.exec() call, but when you run it in a cmd window, the window closes when the batch file completes, because the call to EXIT exits the entire shell. I guess i'm just wondering, am i correct in assuming the exit value returned to the java process is going to be the exit value of the shell in which the batch file is running? I need to have the exit value actually indicate whether the batch file ran successfully or not, and if i have to put in the EXIT %ERRORLEVE% (which exits the cmd shell with the exit value of the last command run), then i'll do that, but if someone knows a better way of doing this, i am all ears. Thanks in advance

    To run any command from java code, the method is
    Runtime.getRuntime().exec( myCommandString )
    Where, myCommandString is something like "/full/pathname/command".
    If the pathname contains spaces (specifically in Windows), e.g. "c:\program files\windows\notepad", then enclose it in quotes within the quoted string. Or pre-tokenize them into elements of an array and call exec(String[] cmd) instead of exec(String cmd).
    From JDK1.3 there are two new overloaded Runtime.exec() methods. These allow you to specify starting directory for the child process.
    Note, there is a gotcha associated with reading output from commands. When the runtime exec's the process, it passes to it 3 streams, for stdin, stdout, and stderr; the out and err are buffered but the buffer size isn't very big. When your process runs, it reads (if needed) from in, and writes to out and err.
    If it doesn't write more than the buffer-size, it can run to completion.
    But if it tries to write more data to one or the other stream than the buffer can hold, the write blocks, and your process hangs, waiting for you to empty the buffer so it can write some more.
    So after the exec call, get the streams, and read from them in a loop until they both hit end-of-stream (don't block on either one, just read whatever is available from each, each loop iteration).
    Then when the streams have ended, call the process.waitFor() method to let it finish dying.
    Now, here is a code snippet how you achieve this.
    String strCommand = "cmd.exe /c " + strCommand;
    // For Solaris / unix it will be
    // String strCommand = "/usr/cobra/sol/runInstaller.sh";
    boolean bWait = true;
    //execute the command
    try
         Runtime r = Runtime.getRuntime();
         Process pr = r.exec(strCommand);
         Process pr = r.exec(callAndArgs);
         BufferedInputStream bis =new BufferedInputStream(pr.getInputStream ());
         int c=0;
         /** Outlet for IO for the process **/
         while (c!=-1)
              c=bis.read();
         /**Now wait for the process to get finished **/
         if(bWait == true)
              pr.waitFor();
              pr.destroy();
    catch(Exception e)
         System.out.println("Could not execute process " + strCommand);
         return(false);

  • Runtime.exec() and Mozilla

    Hi all. I'm not sure if this is the correct forum for this question but I use Runtime.exec() to create a new mozilla process. I have no problem creating the process itself but I need to have a way to communicate with the process to determine whether or not a local file has been successfully loaded into the browser. I programmatically load some html content in mozilla and I need to get the current "state" of the browser (i.e. is the content fully loaded and displayed on the screen or is mozilla still busy loading the html file?). I figure that the only way to determine this state is to get the Processes input stream and to read data from that stream but I don't know if mozilla writes data to it's output stream that indicates what state the application is in. Does anybody have a solution to this problem (Whether using streams or some other approach)? Thanks in advance.

    It may be possible to hack Mozilla to get that sort of information, although most likely its security is good enough to prevent attacks of that kind. But in any case Runtime.exec() isn't going to help.

  • Runtime.exec and locked window

    So I'm working in a Swing application guaranteed to run only on Windows systems using Java 1.6 u 7. The users want a help button to launch a local web browser and point to the company's web site.
    After reading online and finding that getDesktop.browse() sometimes crashes in that version of Java, I use Runtime.exec("rundll ...") to kick off the local browser with the appropriate web address.
    The browser comes up appropriately, but the original Swing application's mouse pointer converts to an hourglass; I can click on the original window and get results but I can't open a new window.
    So I create a short thread implementing the Runnable interface and put the Runtime.exec call in that thread; I assume the problem is that the process is interfering with the GUI thread, and putting the Runtime.exec call in a separate thread will clear the problem up. It doesn't work; I still have the hourglass.
    I read online that some processes require that their input and error streams be consumed, or they may block; That shouldn't be a problem with internet explorer, but I add two threads to consume those streams; still no change.
    I also tried getDesktop().browse() anyway, and in a separate thread, and had the same problem.
    Does anyone have any suggestions?
    Respectfully,
    Brian P.

    Okay.
    First, let's look at the basic client.
    As you can see, when asked to show a window,
    it puts it in a separate thread for rendering:
    public class Client     
    // Show one example method
         private void showNewWindow(Window window)
              ourLogger.info("New request to display window: " + window.getClass().getName());
              if (window instanceof ClientWindow)
                   try
                        ((ClientWindow) window).bindFrames();
                        ((ClientWindow) window).setClient(this);
                        if (window instanceof ClientJDialog)
                             window = new ClientJDialog((ClientJDialog) window);
                        else
                             correctSize(window);
                        showCenter(window);
                        synchronized(myWindows)
                             myWindows.add(window);
                        counter = 0;
                        thread.hide();
                   catch (Exception re)
                        ourLogger.error("Client error while trying to show window", re);
                        ((ClientWindow) window).unbindFrames(false);
              else
                   throw new Error(window.getClass().getName() + " is NOT an instance of ClientWindow");
    // Snip some more
    At this same level on this class, I had originally put a showHelp() procedure with a single
    command thus:
         public void showHelp()
              Desktop.getDesktop().browse(java.net.URI.create(<help web site>));
    Simple, eh? But that gave me the hourglass as discussed. So I pushed it into a new thread.
    It eventually mutated thus:
         public void showHelp()
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
              //windows only
              Runtime rt = Runtime.getRuntime();
              Process p = rt.exec("rundll32 url.dll,FileProtocolHandler " + "<help URL>");
              StreamGobbler s1 = new StreamGobbler ("stdin", p.getInputStream ());
              StreamGobbler s2 = new StreamGobbler ("stderr", p.getErrorStream ());
              s1.start ();
              s2.start ();
              try {
              p.waitFor();
              } catch (java.lang.InterruptedException e) {}
    So as you can see, I ditched Desktop from Runtime and added a pair of stream consumers
    to ensure I wasn't having the stream problem our second poster discussed. Still no joy.
    I eventually replaced the url call with an attempt to invoke a simple batch file which
    did nothing, and I still had the same problem. I still have an hour glass, even when
    the process has been pushed into a new thread as you can see.
    Respectfully,
    Brian P.
    Edited by: pendell on Apr 16, 2010 3:14 PM

  • [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 and exitValue

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

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

Maybe you are looking for

  • HR read infotype

    Hi friends I have to read recent (last) record from the following HR tables/infotypes. Shall I use RP_PROVIDE_FROM_LAST macro? Is there any other other good way to read data? Please give me some sample code. I will appreciate ur great help. PA0001 PA

  • Refreshing screen prior to WEBUTIL reading file

    Hi, I have an application running through OC4J at the moment. When I press the button it WEBUTIL grabs the file and processes line by line via a stored procedure. The problem is, as soon as I press the button the web page goes grey and only the butto

  • Always have to manually re-connect Outlook 2007 mail account

    I get my office mail from an Outlook server and have set up the mail account as an Office 2007 account. I used to have it set up as an IMAP account, and this problem didn't occur. So every time I open up my laptop, all the other mail accounts re-conn

  • Change html to xml

    hello everybody im just a novce here very new to jsp and xml. Could someone teach how to make html to xml. Actually html is to display mysql data but I want it on xml could somebn\ody help here is the code this is a jsp file. <%@ page import="java.sq

  • SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

    I'm pretty sure this is a common question, but i still cant seem to find a solution even after a couple days of searching google. I checked my connection strings several times. The port number is 1433 and the database name is correct. In fact, I only