Stuck On Runtime.exec() with cmd.exe

I've done my best to look through the forums and implement what's been said but I'm getting a problem where my whole Java program freezes when the exec() is executed. Can anyone tell me what I'm missing or have misunderstood ?
        try
            Process runSmodels = Runtime.getRuntime().exec("C:\\Windows\\System32\\cmd.exe lparse predict.pl | smodels 0");
            String smodelsOutput = new String();
            BufferedReader smodelsReader = new BufferedReader(new InputStreamReader(runSmodels.getInputStream()));
            String outputLine = smodelsReader.readLine();
            while(outputLine != null)
                smodelsOutput += outputLine;
                outputLine = smodelsReader.readLine();
            smodelsReader.close();
            System.out.println(smodelsOutput);
        catch(IOException exc)
            JOptionPane.showMessageDialog(rootPane, "Could not access Smodels.", "System Call Error", JOptionPane.ERROR_MESSAGE);
        }

DarioAtUOW wrote:
Pitfall 1 : Calling .exitValue(). My code doesn't do that.
Pitfall 2 :Not enptying relevant streams. I do empty the input stream.
Pitfall 3 : Assuming a command is an executable program. I don't do that, cmd.exe is in my command string explicitly.
Pitfall 4 : As above in Pitfall 3.
So, why accuse me of not reading the article ? You probably have many years of experience at Java, unlike me, who is just starting out with it at university.Pitfall 2 : Even though you are processing stdout you are not processing stderr! Always always always process both. This may or may not be the cause of your problem but by copying the process stderr to your System.err you may see why your process is stuck.
Even Clippy, the Microsoft Office Assistant, could answer questions better than you have attempted to do.Ouch, I'm cut to the bone on your razor sharp wit. Phuck you.

Similar Messages

  • Runtime.Exec with cmd and problem in waitFor

    Hi
    I am running
    Process p1 = Runtime.getRuntime().exec("cmd /c start /min <some.exe> <args to exe>");
    then I am checking
    Int ExitVal = p1.waitFor;
    If (ExitVal != 0) and so on.
    However, the problem is that the p1.waitFor does not really block the thread. It returns 0 and the program continues even though the some.exe has still not completed its execution.
    My guess is that Java is giving the exitcode of cmd.exe and not some.exe.
    If this analysis is correct, I am stumped. How do I get the exit code of some.exe?
    If my analysis is wrong, please help me in the right direction.
    Regards
    Shreekar

    "Enables a user to start a separate window in Windows
    from the MS-DOS prompt."<p>
    Again, I read it afterwards. However, another funny thing is happening now. Initially my command was
    "cmd start /min (some.exe) (some args) > somefile.txt"
    (I know I missed to show the output redirection in my original post.)
    </p>
    <p>
    Then I removed "start /min", it is working as expected.
    Then I removed the output redirection and now it hangs !!!
    I put back the output redirection and it is working. Does the output redirection make it wait in some way and force it to exit gracefully?
    </p>
    Any ideas?

  • 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() with .bat-files in a jar

    Hi All,
    I've written a java-Program, which calls .bat-files per Runtime.exec() for some OS-specific tasks.
    Everything works fine, but if I want to pack the whole code and the .bat-files into several jars, I can't get the bat-files to run. I have tried to get it to work with "getClass().getResource()" as I do the same for my Images, and the returned URL seems to be OK so far (something like jar:file:/c:/test.jar! testpkg/test.bat). I converted this URL into a String and tried to run Runtime.exec() with it, but I always get a Runtime-Exception.
    The String looks exactly like the URL, when I print them to console.
    These bat-files are essential for the application and I would not try to pack them into a jar if I hadn't to distribute this application as a signed applet to unknown users, too.
    I hope there is anyone out there who can tell me if and how it is possible to run an external program out of java, which is packed into a jar, so thanx in advance to any helpful replies.
    acdeka

    You can't run the .bats simply because the shell can't access it. You tell it to run a file that simply doesn't exist in the OS.

  • Runtime.exec() with language specific chars (umlauts)

    Hello,
    my problem is as follows:
    I need to run the glimpse search engine from a java application on solaris using JRE 1.3.1 with a search pattern containing special characters.
    Glimpse has indexed UTF8 coded XML files that can contain text with language specific characters in different languages (i.e. german umlauts, spanish, chinese). The following code works fine on windows and with JRE 1.2.2 on solaris too:
    String sSearchedFreeText = "T&#252;r";
    String sEncoding = "UTF8";
    // Convert UTF8 search free text
    ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(osByteArray, sEncoding);
    w.write(sSearchedFreeText);
    w.close();
    // Generate process
    String commandString = "glimpse -y -l -i -H /data/glimpseindex -W -L 20 {" + osByteArray.toString() + "}";
    Process p = Runtime.getRuntime().exec(commandString);
    One of the XML files contains:
    <group topic="service-num">
    <entry name="id">7059</entry>
    <entry name="name">T&#195;&#188;rverkleidung</entry>
    </group>
    Running the java code with JRE 1.2.2 on solaris i get following correct commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T&#195;&#188;rverkleidung}
    --> glimpse finds correct filenames
    Running it with JRE 1.3.1 i get following incorrect commandline
    glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T??rverkleidung}
    --> glimpse finds nothing
    JRE 1.2.2 uses as default charset ISO-8859-1 but JRE 1.3.1 uses ASCII on solaris.
    Is it possible to change the default charset for the JVM in solaris environment?
    Or is there a way to force encoding used by Runtime.exec() with java code?
    Thanks in advance for any hints.
    Karsten

    osByteArray.toString()Yes, there's a way to force the encoding. You provide it as a parameter to the toString() method.

  • Interacting with cmd.exe

    Hi all,
    i dunno if this has been asked before, but my problem is to let the user interact with an executable ran via "cmd.exe /c executable".
    i have an executable program that awaits a response from the user, but when i used the Streams provided by java.lang.Process after many scenarios i noticed that the process inputStream provides me with the output only when the program is finished, while it returns no text while the program is waiting for response
    as an example, my problem looks like :
    try {
                Process p = Runtime.getRuntime().exec("cmd.exe /c mysql -u toto");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));
                  String s = null;
                while ((s = reader.readLine()) != null) {
                        System.out.println(s);
    } catch (IOException ex) {
                ex.printStackTrace();
    }the mysql command would show "enter password : " or something like that, but this program will not show it...unless the mysql is finished
    any ideas? thanks :)

    that's right, i tried to look for classes that provide "live streams" in java.io ... i thought the PipedReader and PipedWriter could do it, but i need to get the program's reader and writer for this (and i don't know how to do that...) or maybe those classes are unnecessary and there is another way to do it?

  • Problem with cmd.exe  /C SET

    Hi:
    I am trying to set environment variables for an exe file in a Java program.
    I am thinking to do:
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd.exe /C set FILEDIR=c:\temp);
    But, I tried cmd.exe /C set FILEDIR=c:\temp on my xp machine dos window and in the java code. The FILEDIR is null.
    Does someone have any idea what went wrong? Anyother better ways to set environment variables in java codes?
    Thanks.

    cmd.exe opens a new command process. The set command will only be effective in this particular process. As soon as the process closes (which will be immediately the set command completes) the value of FILEDIR will be lost.
    You can see this by doing cmd /K set FILEDIR=c:\temp. This will leave the command process open and you see what the value of FILEDIR is.

  • Runtime.exec with spaces not working EVEN using String[]!!

    Hi everyone,
    I need to start the rmi registry from some code,and i need to pass it the classpath of two jars when initialising it. My problem is that the paths I set aren't taken when they contain a space.
    Here's the code:
    <code>
    String rmiRegistryCommandLine[] = new String[] {
    + System.getProperty("java.home")
    + "\\bin\\rmiregistry.exe\"",
    "-J-Djava.class.path=\""+System.getProperty("user.dir")+"\\MyJar.jar\"",
    "1099"};
                                            Runtime.getRuntime().exec(rmiRegistryCommandLine);
    </code>
    I know that Runtime.exec(String) tokenizes the input, which is why I'm not using it, but Runtime.exec(String[]) isn't supposed to tokenize the input. System.getProperty("user.dir") can contain a space, so I put quotes around that, but I need the -J-Djava.class.path in the same string. I tried breaking it up into two more separate strings but it didn't even run for normal non-space paths then. I am sure that if the whole -J-Dblah....upto MyJar.jar was in quotes then it would work, but I need the classpath in quotes separately as it could contain a space.
    Can anyone help me get this working?

    Ya, that's fine but the command line I want to pass is:
    d:\j2sdk1.4.0\bin\rmiregistry.exe -J-Djava.class.path=d:\my dir with spaces\MyJar.jar;d:\my more dir with spaces\MyJar2.jar 1099
    If I say
    arg[0]="d:\\j2sdk1.4.0\\bin\rmiregistry.exe";, that's finebut arg[1] is the problem
    if I say
    arg[1]="-J-Djava.class.path=d:\\my dir with spaces\MyJar.jar; d:\\my more dir with spaces\\MyJar2.jar";, then it definitely won't work on 9X machines and probably not on NT.
    if I break up arg[1] into:
    arg[1]="-J-Djava.class.path=";
    arg[2]="d:\\my dir with spaces\\MyJar.jar";
    arg[3]=";";
    arg[4]="d:\\my more dir with spaces\\MyJar2.jar";I'll need to put quotes around the two individual two class paths or else it won't work.
    I find though that if I put the classpath as follows
    d:\"my dir with spaces"\MyJar.jar then it seems to work.
    I think a regular expression function to search for any directory with spacees and then put quotes around it and reinsert it into the path would be the solution.

  • Runtime.exec() with get command output

    hi,
    How can i get output of command which i run with runtime.exec().
    p.e.:
    Process p;
    Runtime r = Runtime.getRuntime();
    p = r.exec("net use \\pc\dir pswd /user:username");
    if command was done succesfully that in cmd is return this:
    "The command completed successfully." I can get this text, but i dont know how.
    Plese help
    thank you
    Palo

    Look at the API for Process

  • System exec with telnet.exe

    I am trying to execute the windows program telnet.exe from the system exec function but I only get error 2 back. I am aware that it indicates that the path of the program is not correct. However when I do the same with notepad.exe which is in the same folder (c:\windows\system32\) it works fine.
    Any ideas?
    /martin
    Attachments:
    telnet.vi ‏14 KB

    Rollerboy wrote:
    Hi again Mark
    I was looking among the examples but I don't seem to  find what you are refering to. Could you please direct me!
    You could search for TCP using the example finder. They have basic examples of servers and clients. Do you have all of your palletes visble? You can view more by selecting additional palletes. View the Functions pallete (View->Functions Pallete) and select the Customize tab. From there make sure you are displaying the Data Communication pallete.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • Runtime.exec() with japanese arguments?

    I'm trying to invoke a C++ executable from java using the Runtime.exec() method. The C++ application accepts a filename as a command line argument & opens the file. This C++ app is unicode enabled i.e. it can accept UTF-16 (wide char) parameters. Howevere, when i invoke this application using Java's Runtime.exec() and specify a japanese file name as an argument, the japanese characters get converted to '?' characters by the time they are received in the C++ application. I'm running this application on Windows 2K, default i.e. English version.
    Looking at the source code of Runtime class, it seems that the exec()
    function makes use of a native helper function - execInternal(). Does
    this function support the entire unicode range?
    Is there any way we can avoid the conversion of japanese characters to '?' characters? Also, is there any other alternative for invoking an external application with Unicode (Say, japanese) arguments?
    Please reply ASAP.
    Thanks!

    I have a very similar problem. I am invoking cvs through Runtime.exec, and I am using it to add and check in files with chinese characters in the name, and it is failing with the following cvs error:
    Could not add resource file &#32435;&#20986; in directory C:\test to repository: cvs add: nothing known about ??
    The error message comes from cvs, and I have been able to track it down to the call string I pass to exec. It is correct when passed in but the command fails. For laughs I tried to call something simpler, like mkdir:
    err mkdir ?? is: The filename, directory name, or volume label syntax is incorrect.
    It seems pretty clear to me that although the callstring is correct, the call to exec fails, and the special characters are replaced with questionmarks, which seems to me to be an encoding issue.
    Did you get any solution to your problem, or does anyoen else have an answer for this?

  • Runtime.exec() with envp[] array

    I ran into an unsual problem.
    If I set an env array variable to something (at least one pair), then certain applications fail to start through Runtime.exec(command[], env[]). For example, my own java classes that require various xml and ftp libraries. The particular exception has been mentioned on the forum ( ie. Unrecognized Windows Sockets error: 10106:).
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    thanks,
    eugene

    >
    It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
    So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
    >
    If you're using 1.5, you can create a java.lang.ProcessBuilder object rather than calling Runtime.exec(). The ProcessBuilder inherits the environment of the calling process, but then allows you to update individual entries.
    In 1.4, I don't believe that you can get a complete copy of the invoker's environment.

  • Issue with cmd.exe.

    Opening cmd.exe and clicking and/or moving the cursor deletes part of the screen. See picture. W10x86

    Mooly01,
    Windows 10 defaults to having QuickEdit mode enabled as a default.  If you want to disable it for all Command Prompts, you will need to de-select it in two places. 
    Right-Mouse click the title bar and choose Defaults.  
    Uncheck QuickEdit Mode.
    Right-Mouse click the title bar and choose Properties.  
    Uncheck QuickEdit Mode.
    Thanks, John Marlin Microsoft Server Beta Team

  • Runtime.exec with a unix shell script

    I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
    Gary

    I think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
    Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
    Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
    Dave

  • Runtime.exec with Unix script

    I want to execute unix script xxx.sh that I write it for running something and I will execute that script via java class I use
    Runtime runTime = Runtime.getRuntime();
    Process procRun = runTime.exec("/xxx/yyyy/testing.sh");
    xxx and yyyy is path in my unix server and testing.sh is unix script
    when I run this class it return true result but that unix script doesn't working or execute following my program in java class
    please help me to solve this problem
    Regards,
    sobig

    when I run this class it return true result but that unix script doesn't
    working or execute following my program in java classwhat do you mean it returns true....
    and how do you know that it does not execute your script.... its probably going to be started as a bg process.... try doing something like creating a directory or something in the script .sh to be sure that it ran.... (just for testing).... im quite sure that it will execute a .sh file like that....

Maybe you are looking for

  • How do i find out who is using my airport express?

    I have an airport express to extend my Wifi coverage and i am sure other people who have asked for the password in the past are still using it. Is there a way to see who is using it, when and block people? I could change the password, but I would lik

  • Error in ACTIVATE_CURRENT_USAGES phase of portal upgrade (NW04 to NW04s)

    hello gurus, i am upgrading Netweaver 04 to netweaver 04s (Enterprise Portal) oracle upgrade from 9.2.0.7 to 10.2.0.1 successfully but i am getting error in 78 phase out 100 in java upgrade program management ACTIVATE_CURRENT_USAGES i am unable to tr

  • Inserting rows in cursor and breaking up when effect date matches

    Hi I have created a table cadreinc (empno varchar2(8), pay number(5), da number(5) , scale varchar2(11), effectdate date , flag varchar2(1)) with values as shown below. 04485816      12800     4200     09300-34800      1-Jan-2006     Y 04485816      

  • 19" lcd dynex tv/dvd combo problem

    I am wondering if anyone can help me with this. I have 2 19" lcd tv/dvd combo... one in each kids room. I mounted em up on the wall so the kids couldn't mess with them. So now heres my problem, both of the tvs when turned on turn off then back on the

  • Returnable packaging a/c posting details

    Hi All experts, could any one of you let me know the correct table to find out the followings: 1. RP(returnable packaging) account header details. 2. RP account item level or transaction details like opening balance, closing balance, bill of lading,