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

Similar Messages

  • Runtime.exec and dialog windows

    I'm using Runtime.exec to launch an exe that may crash due to runtime errors (such as division by zero). When this appens a dialog window shows up, waiting for the user to close it. (I'm running the program under Win98). Is there a way to avoid this?

    I think the only way should be fixing the exe bug!
    There is no way, I suppose.
    Ciao!

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

  • 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 opens new window

    Hi, I am using Runtime.exec to run an external application in Windows2000. � can read its output and i can destroy it without any problems.
    But when i run my java application with javaw , the external application i run with rt.exec opens new window(without output texts, empty) . just output command windows which opens when i run the external app. from a command prompt.
    If i run my java application with java.exe then then external application DO NOT open new window and run correctly. But this time my java window stays on desktop, and that's not any good for a Windows Application.
    In both cases everything runs OK. The only problem is the command prompt windows.
    Is there a solution when working with javaw.exe ? or hide the window when running with java.exe
    Thanks all.

    bug with ID: 4244515

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

  • Runtime.exec() for different Windows versions ?

    Hello all.
    I'm currently developing a Java program that uses Runtime.exec() to launch a MS-DOS application (the old MS-Kermit). It works fine under Windows ME and Java 1.3.1 but the very same code fails to work under Windows 2000. That's very bad for me, since my program should work on all windows platforms from 95 up to XP (and NT).
    My question is : can I trust Runtime.exec() or am I damned to write different versions of the same command for different operating systems ?
    Thanks.

    Runtime is not os independent, so yes, it has to accomodate the os differences. There is an enhancement request on the subject, tho.
    Search the forums, there is code that handles the differences posted.

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

  • Runtime.exec() opening dos window.

    I heard that in newer version of java (>java 1.2 ) if Runtime.exec() is used to execute some native program, a black dos promt is popped up automatically and closed when the execution of the native program is completed.
    Will this happen every time I use Runtime.eceX()? is there a way to avoid this opening of dos prompt.

    It will vary by os version. Read up on the use of the command or cmd statements from the os help information, and on the os's start command (may not exist in all os's)
    Experiment fron the commandline to see what happens.

  • Firefox 22 changed and locked Windows 7 title bar (big and bold)

    Not sure why the decision was made to map to Windows settings, but the upgrade from FF21 to FF22 has also changed and locked my Windows 7 Toolbar font settings (active and inactive). They are now big and bold. While I can change the color, I cannot change the font, font size, or unbold (stays bold regardless of "B" being highlighted or not).
    Not sure if anyone else has this issue, but it just made my Windows ugly.
    See the image. Color is changed, but the font isn't a size 6 and it's also bold when shouldn't be.

    Fix by reverting to a pre-FF22 registry backup entry for:
    HKEY_CURRENT_USER
    Control Panel
    Desktop
    WindowsMetrics
    You can't really modify the entries in regedit as they are hex data values. But this did (after a few hours) solve my problem.

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

Maybe you are looking for

  • Can i use iCloud with one apple id but app store with another; especially on iOS 6?

    My household has multiple devices.  I own iPhone and iPod, both on iOS 5.1.1, and iCloud (used for apps, iMessage, and backup.) I almost never buy music, but I buy some apps. My SO has iPhone (also on 5.1.1), and she uses my apple id for purchases (m

  • Playing a playlist with multiple albums in Grid View in iTunes 8

    Hi All, Here is a situation I came across, that was quite unexpected compared to the behaviour in iTunes 7. Suppose I have a playlist with multiple artists/albums. I have this playlist in Grid View. I choose this playlist from the left side navigatio

  • Hide variant button in menu toolbar

    Hi experts I would hide the variant button in the menu toolbar for the transaction vl10g Link:[http://img104.imageshack.us/img104/5439/vl10g.png] somebody can help me?? thanks Marco

  • BI (BOE) XI R3.1 (Linux) Server Migration -  Update BOE base directory path

    Hello, Performing a server migration using BOE XI R3.1 (from BOE XI R3.1 to same release BOE XI R3.1) on Linux Platform. After performing a data restore, the BOE server executables could not be launched (do not start) due to different BOE base direct

  • Retrieve data from vector to jtextfield.

    hi guys, i have made a simple database program using JDBC...i display data from database into JTable...but i want to allow the user to change a record for e.g. if the user selects a record from jtable to change its details such as name etc...then i w