Runtime exec fail()

I exec() an shell script, which is not executable. I would like to know how can I handle the exception. I would like to use the getErrorStream() when there is an error. I do not know how do I set it up?
Thanks

From the Runtime.exec documentation:
Starting an operating system process is highly system-dependent. Among the many things that can go wrong are:
The operating system program file was not found.
Access to the program file was denied.
The working directory does not exist.
In such cases an exception will be thrown. The exact nature of the exception is system-dependent, but it will always be a subclass of IOException.
Catch and handle the exception. Follow the methods in this tutorial:
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Similar Messages

  • Runtime.exec() fails sometime to execute a command

    Hello,
    I have a program thats using Runtime.exec to execute some external programs sequence with some redirection operators.
    For e.g, I have some command as follows;
    1 - C:\bin\IBRSD.exe IBRSD -s
    2 - C:\bin\mcstat -n @punduk444:5000#mc -l c:\ | grep -i running | grep -v grep |wc -l
    3 - ping punduk444 | grep "100%" | wc -l
    ...etc.
    These command in sequence for a single run. The test program makes multiple such runs. So my problem is sometimes the runtime.exec() fails to execute some of the commands above (typically the 2nd one). The waitFor() returns error code (-1). That is if I loop these commands for say 30 runs then in some 1~4 runs the 2nd command fails to execute and return -1 error code.
    Can some one help me out to as why this is happening? Any help is appreciated
    Thanks,
    ~jaideep
    Herer is the code snippet;
    Runtime runtime = Runtime.getRuntime();
    //create process object to handle result
    Process process = null;
    commandToRun = "cmd /c " + command;
    process = runtime.exec( commandToRun );
    CommandOutputReader cmdError = new CommandOutputReader(process.getErrorStream());
    CommandOutputReader cmdOutput = new CommandOutputReader(process.getInputStream());
    cmdError.start();
    cmdOutput.start();
    CheckProcess chkProcess = new CheckProcess(process);
    chkProcess.start();
    int retValue = process.waitFor();
    if(retValue != 0)
    return -1;
    output = cmdOutput.getOutputData();
    cmdError = null;
    cmdOutput = null;
    chkProcess = null;
    /*******************************supporting CommandOutputReader class *********************************/
    public class CommandOutputReader extends Thread
    private transient InputStream inputStream; //to get output of any command
    private transient String output; //output will store command output
    protected boolean isDone;
    public CommandOutputReader()
    super();
    output = "";
    this.inputStream = null;
    public CommandOutputReader(InputStream stream)
    super();
    output = "";
    this.inputStream = stream;
    public void setStream(InputStream stream)
    this.inputStream = stream;
    public String getOutputData()
    return output;
    public void run()
    if(inputStream != null)
    final BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream), 1024 * 128);
    String line = null;
    try
    while ( (line = bufferReader.readLine()) != null)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.DEBUG,line);
    //output += line + System.getProperty(Constants.ALL_NEWLINE_GETPROPERTY_PARAM);
    output += line + "\r\n";
    System.out.println("<< "+ this.getId() + " >>" + output );
    System.out.println("<< "+ this.getId() + " >>" + "closed the i/p stream...");
    inputStream.close();
    bufferReader.close();
    catch (IOException objIOException)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("io_exeception_reading_cmd_output")+
    objIOException.getMessage());
    output = ResourceString.getString("io_exeception_reading_cmd_output");
    else
    output = "io exeception reading cmd output";
    finally {
    isDone = true;
    public boolean isDone() {
    return isDone;
    /*******************************supporting CommandOutputReader class *********************************/
    /*******************************supporting process controller class *********************************/
    public class CheckProcess extends Thread
    private transient Process monitoredProcess;
    private transient boolean continueLoop ;
    private transient long maxWait = Constants.WAIT_PERIOD;
    public CheckProcess(Process monitoredProcess)
    super();
    this.monitoredProcess = monitoredProcess;
    continueLoop =true;
    public void setMaxWait(final long max)
    this.maxWait = max;
    public void stopProcess()
    continueLoop=false;
    public void run()
    //long start1 = java.util.Calendar.getInstance().getTimeInMillis();
    final long start1 = System.currentTimeMillis();
    while (true && continueLoop)
    // after maxWait millis, stops monitoredProcess and return
    if (System.currentTimeMillis() - start1 > maxWait)
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    return;
    try
    sleep(1000);
    catch (InterruptedException e)
    if (ResourceString.getLocale() != null)
    Utility.log(Level.ERROR, ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    System.out.println(ResourceString.getString("exception_in_sleep") + e.getLocalizedMessage());
    else
    System.out.println("Exception in sleep" + e.getLocalizedMessage());
    if(monitoredProcess != null)
    monitoredProcess.destroy();
    //available for garbage collection
    // @PMD:REVIEWED:NullAssignment: by jbarde on 9/28/06 7:29 PM
    monitoredProcess = null;
    /*******************************supporting process controller class *********************************/

    Hi,
    Infact the command passed to the exec() is in the form of a batch file, which contains on of these commands. I can not put all commands in one batch file due to inherent nature of the program.
    But my main concern was that, why would it behave like this. If I run the same command for 30 times 1~3 times the same command can not be executed (returns with error code 1, on wiun2k pro) and rest times it works perfectly fine.
    Do you see any abnormality in the code.
    I ahve used the same sequence of code as in the article suggested by
    "masijade". i.e having threads to monitor the process and other threads to read and empty out the input and error streams so that the buffer does not get full.
    But I see here the problem is not of process getting hanged, I sense this because my waitFor() returns with error code as 1, had the process hanged it would not have returned , am I making sense?
    Regards,
    ~jaideep

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

    Hi,
    I have a process with many executables which work together to copy a script to another machine, execute it and get back the results. I am using Runtime.exec to execute the process. The files are stored in the directory "/opt/mx/myDir".
    Below are two scenarios. One works and the other doesnt.
    1. Working case.
    #cd /opt/mx/myDir
    #java myJavaClass.
    2. Failing case.
    #java myJavaClass.
    The issue is that myJavaClass is part of another project and hence I cannot "cd" to /opt/mx/myDir. So it executes at some directory and fails.
    Hence I tried ProcessBuilder.directory(file) - This fails too.
    I have no logs or anything as the other process is not mine.
    Any help on debugging this will be great.
    Thanks.

    Apologies if this is too obvious, but is your command
    #java myJavaClass.
    or
    java myJavaClass
    The trailing period is wrong.

  • Runtime.Exec() fails -- Through java stored procedure in Oracle8i

    HI,
    I HAVE A JAVA STORED PROCEDURE WHICH EXECUTES
    A HOST COMMAND USING Runtime.Exec().
    BUT IT IS NOT WORKING.
    RIGHTS FOR THE USER HAVE BEEN GIVEN USING
    Dbms_grant_persmission(). The database in on
    SUN SOLARIS. THE EXITVALUE OF THE RUNTIME.EXEC COMMAND IS 255(SEGMENTATION
    ERROR - CORE DUMPED).
    PLEASE LET ME KNOW WHERE THE PROBLEM LIES. THE FUNCTION IS WORKING WELL IF THE DATABASE IS ON NT PLATFORM BUT FAILS TO WORK WHEN I STORED THE PROCEDURE IN A DATABASE RUNNING ON SUN SOLARIS AND TRIED TO EXECUTE A SOLARIS COMMAND THROUGH THE PROCEDURE.
    Thanks for ur interest!
    with best regards,
    Mathan

    I have similar problem on HP-UX, I would appreciate if you
    somehow were able to solve it.
    Thanks
    Rahul Shah

  • Runtime.exec fails to launch C++ application

    A java application launches a C++ Windows based application, providing it with arguments on the command line. This application is supposed to start, to execute something and to exit.
    This is working as long as the java code runs from the command prompt.
    When the java code is running as part of a Java Windows 2000 service, the C++ application starts but enters a loop and never returns. It consumes all CPU and waits for something that I could not figure out. I can just see the process in the Task Manager.
    Windows 2000 service is configured as loging on a user account.
    I have not the code of the C++ application and cannot modify it.
    Here is the piece of code that starts this C++ Application :
    //Start the command and wait for completion
    try{
    java.lang.Process submitProcess = Runtime.getRuntime().exec(command);
    submitProcess.waitFor();
    if(submitProcess.exitValue() == 0){
    return;
    } else{
    System.out.println("exitValue = " + submitProcess.exitValue());
    } catch(Exception e){e.printStackTrace();

    For information, wrapping input and error streams did not return any information.
    Doing further testing, I found that this application - a viewer that I use for its command line print functionality- starts looping when I pass as argument a DWG file. If I ask it to print .DOC or .XLS or .HTML ... files, it works.
    If I start the application from Java code at command prompt, it works even with this DWG file and it does not ask for anything.
    My conclusion is that the loop comes from a component used for Autocad conversion when the Java code launching the application is started as Windows 2000 service.

  • The Runtime.exec methods doesn't work well on Solaris ???

    I have two threads and I set the different running time.
    I use Runtime.exec to a run the command and use Process to get the process.
    It works properly in the windows2000 platform.
    However, when I transfer the platform to Solaris...and run the program...
    Two threads always at the same time....It is very wired....I always debug
    for 2 days....
    (at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
    all of them don't work.....
    If I close the Runtime.exec..........Everything works well......)
    And I study the API. I found this message...
    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 Win32, or shell scripts. The created subprocess does
    not have its own terminal or console.
    Could someone share her/his experience.....:(
    And if any other way I can run command inside java code instead of
    Runtime.exec.....???
    Please reply my mail to [email protected] I do appreciate your kindly &
    great help!!!!!!!!
    This is my code.......
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    * <p>ServerThread1</p>
    * <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
    class ServerThread1 extends Thread{
    private ServerAgent Sa;
    public ServerThread1 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa; file://Assign ServerAgent reference Sa
    public void run(){
    while(true){
    try{
    Thread.sleep(5000);
    catch (Exception e){
    System.out.println("ServerThread1 fails");
    System.out.println("Thread1 is running.");
    try {
    Runtime rt1 = Runtime.getRuntime();
    Process proc1 = rt1.exec("mkdir"); ------>If I close
    rt1.exec , two threads works seperately...........:(
    catch (Exception e) {
    System.out.println("Thread1 Error");
    class ServerThread2 extends Thread{
    private ServerAgent Sa;
    public ServerThread2 (String Name, ServerAgent Sa){
    super(Name);
    this.Sa = Sa;
    public void run(){
    while(true){
    try{
    Thread.sleep(15000);
    catch (Exception e){
    System.out.println("ServerThread2 fails");
    System.out.println("Thread2 is running.");
    try {
    Runtime rt2 = Runtime.getRuntime();
    Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
    the rt2.exe, two threads work seperately....
    catch (Exception e) {
    System.out.println("Thread2 Error");
    public class ServerAgent{
    private Vector v1 = new Vector();
    private Vector v2 = new Vector();
    private Hashtable currentData = new Hashtable();
    private static String startUpSwap = null;
    private static String startUpMem = null;
    public static void main(String[] arg) {
    ServerAgent s = new ServerAgent();
    ServerThread1 st1 = new ServerThread1("Thread1",s);
    ServerThread2 st2 = new ServerThread2("Thread2",s);
    st1.start();
    st2.start();

    If I close the Runtime.exec..........Everything works
    well......)You don't empty the output of the command, that blocks the process.
    A citation from
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    Why Runtime.exec() hangs
    The JDK's Javadoc documentation provides the answer to this question:
    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.
    Try out something like this:
    String s;
    try {
       Process myProcess =
       Runtime.getRuntime().exec("ls -l"));
       DataInputStream in = new DataInputStream(
              new BufferedInputStream(myProcess.getInputStream()));
        while ((s = in.readLine()) != null) {
            out.println(s);
    catch (IOException e) {
        out.println("Error: " + e);
    }Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
    Regards,
    Marc

  • Runtime.exec() - Need to execute unix command through pipe

    I want to execute something like this from Runtime.exec() :
    tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
    If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
    How can I achieve this?

    The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
    Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
    Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

  • How to make Runtime.exec call Linux exec?

    Howdy,
    I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs.
    Here's the command:
    Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;");
    It's failing, not sure why, the exitCode is 1 instead of 0. I'm not sure if it's because I have to escape the '\' character, or if it's because I am calling Linux's 'exec' function within a Java exec() call, or something else entirely.
    The easiest thing to do would be to just use rm, but that doesn't seem to be an option. With rm it seems to be all or nothing -- If I try:
    rm -rf *.vcs
    it fails if it doesn't find a file with that extension in the start directory (even though I've specified -r). But if I enter:
    rm -rf *
    it nukes my directories AND files, something I don't want to happen. I realize this is a Linux thing, I'm just explaining it here as background, just in case.
    Anyway, so is there a way to do this? Perhaps with another system call, without using Linux's exec()?
    Many thanks
    Bob

    import java.io.*;
    public class ExecutingALinuxCommand
        static class PipeInputStreamToOutputStream implements Runnable
            PipeInputStreamToOutputStream(InputStream is, OutputStream os)
                is_ = is;
                os_ = os;
            public void run()
                try
                    byte[] buffer = new byte[1024];
                    for(int count = 0; (count = is_.read(buffer)) >= 0;)
                        os_.write(buffer, 0, count);
                catch (IOException e)
                    e.printStackTrace();
            private final InputStream is_;
            private final OutputStream os_;
        public static void main(String[] args)
            try
                String dir = System.getProperty("user.home") + "/work/dev";
                String[] command = {"sh","-c", "find " + dir + " -name '*.java' -exec grep -l Runtime {} \\;"};
                final Process process = Runtime.getRuntime().exec(command);
                new Thread(new PipeInputStreamToOutputStream(process.getInputStream(), System.out)).start();
                new Thread(new PipeInputStreamToOutputStream(process.getErrorStream(), System.err)).start();
                int returnCode = process.waitFor();
                System.out.println("Return code = " + returnCode);
            catch (Exception e)
                e.printStackTrace();
    }

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • Runtime.exec()

    Please check the code.
    String []envp = {"JAVA_HOME=C:/AdventNet/Simulator5_0/jre", "STKT_HOME=C:/AdventNet/Simulator5_0", "LD_LIBRARY_PATH=C:/AdventNet/Simulator5_0/lib",
                                   "PATH=%PATH%;C:/AdventNet/Simulator5_0/lib",
                                   "classpath=C:/AdventNet/Simulator5_0;C:/AdventNet/Simulator5_0/conf;C:/AdventNet/Simulator5_0/jars/AdventNetNPrevalent.jar;C:/AdventNet/Simulator5_0/jars/AdventNetLauncher.jar;C:/AdventNet/Simulator5_0/jars/AdventNetUpdateManagerInstaller.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentRuntimeUtilities.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentUIUtilities.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentUtilities.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentSimulatorRuntime.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentSimulator.jar;C:/AdventNet/Simulator5_0/jars/AdventNetNetworkSimulator.jar;C:/AdventNet/Simulator5_0/jars/AdventNetNDT.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSimulatorDB.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSimulatorUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSimulatorUIUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgentUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetAgent.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSnmp.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSnmpAgent.jar;C:/AdventNet/Simulator5_0/jars/AdventNetSnmpAgentTools.jar;C:/AdventNet/Simulator5_0/jars/jaxp.jar;C:/AdventNet/Simulator5_0/jars/xalan.jar;C:/AdventNet/Simulator5_0/jars/MibBrowser.jar;C:/AdventNet/Simulator5_0/jars/crimson.jar;C:/AdventNet/Simulator5_0/jars/jython.jar;C:/AdventNet/Simulator5_0/jars/JimiProClasses.zip;C:/AdventNet/Simulator5_0/jars/ApiUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetTL1.jar;C:/AdventNet/Simulator5_0/jars/AdventNetTL1Agent.jar;C:/AdventNet/Simulator5_0/jars/AdventNetTL1AgentTools.jar;C:/AdventNet/Simulator5_0/jars/AdventNetTL1Tools.jar;C:/AdventNet/Simulator5_0/jars/AdventNetLogging.jar;C:/AdventNet/Simulator5_0/jars/AdventNetProBeansBeanInfo.jar;C:/AdventNet/Simulator5_0/jars/AdventNetProBeans.jar;C:/AdventNet/Simulator5_0/jars/AdventNetUI.jar;C:/AdventNet/Simulator5_0/jars/AdventNetUIBeanInfo.jar;C:/AdventNet/Simulator5_0/jars/mysql_connector.jar;C:/AdventNet/Simulator5_0/jars/AdventNetCCLUtils.jar;C:/AdventNet/Simulator5_0/jars/AdventNetCCLXMLParser.jar;C:/AdventNet/Simulator5_0/jars/AdventNetTftp.jar;C:/AdventNet/Simulator5_0/jars/ftp.jar",
                                   "THREADS_FLAG=native", "JAVA_COMPILER=NONE" };
              //String cmd = "%JAVA_HOME%/bin/java -mx200M  -Dpython.home=./jython -Djython.jar=./jars/jython.jar -Dpython.packages.paths=jython.jar,sun.boot.class.path com.adventnet.simulator.netsim.NetworkSimulator  -net networks/nn/nn.net %*";
              String cmd = "C:/AdventNet/Simulator5_0/jre/bin/java -mx200M  -Dpython.home=C:/AdventNet/Simulator5_0/jython -Djython.jar=C:/AdventNet/Simulator5_0/jars/jython.jar -Dpython.packages.paths=jython.jar,sun.boot.class.path com.adventnet.simulator.netsim.NetworkSimulator  -net networks/NetworkDemo/NetworkDemo.net >jerr.txt";
              try {
                   Runtime.getRuntime().exec(cmd,envp,new File("C:/AdventNet/Simulator5_0/"));
              } catch(Exception e) {
                   e.printStackTrace();
              }The same thing if I try in command line prompt of Windows XP, I dont find any problem. The java class executes. But when I try with above approach it fails. But I dont find any error or problem. Please tell me how could I check the output, the error executed by the command provided in exec() method. If I can see the output, I can understand the problem.

    I can't be bothered to read all that, and you really should have provided a better explanation of what the problem is.
    However, at a guess, I think it might be the %% variable names. Those are expanded by the command shell when you run cmd.exe, but when you just pass them as args to Runtime.exec, it doesn't expand them.
    I know for a fact a similar thing happens when you try to use $ variable names on Unix, but I'm not very familiar with cmd.exe, so this is just a guess.
    You might try either replacing them here with their System.getEnv() values, or changing your command to cmd.exe, and then passing the rest--including the invocation of the vm--as args. I think it's something like "cmd.exe /c C:\\...blah...\\java ...etc...." but check the help on cmd.exe /? for details.

  • Why is Runtime.Exec not perfekct?

    Hi!
    I need to execute a program from java using Runtime.Exec(). I have done everything right with redirection the output stream and read it from a seperate thread. This works for most of the programs I tried, but not for all. Sometimes I miss some of the output.
    But if I use redirection to a file from the shell it works perfect.
    (i.e. /bin/pramsim > outfil)
    Why is this? Why isn't Runtime.exec as good as shell redirection?
    /Karl

    Ok sorry, here is some more detalis.
    The program( pramsim) prints to both standard output and standard error. Output written to stderr does always work. But output so stout fails quite often. After some research I found out that pramsim is using the function printf(...) which is bufferd by default. So I only get the output when the program prints alot, so the buffer gets full.
    Can I in some way turn buffering off from java? Found a C function called setbuf(1,null) which turns buffering off. But this means I have to changes the code to pramsim, and I want to avoid that!
    I also wonder: How does redirection in the shell make this work. I guess buffering is turned off when I redirect to a file using 'pramsim > outfil'. (maybe this is more a C question but I hope that I can get some help here)
    /Karl

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

  • Question about Runtime.exec

    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

    Runtime.exec is a J2SE API. It's not really specific to WLS.
    You can read about it here:
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Runtime.html
    It looks like you are starting a JMS Server in a separate process and
    that process is crashing.
    (You could of course just use WLS's JMS Server instead :>)
    -- Rob
    Iris Qu wrote:
    Rob,
    Thanks for your help.
    I asked a question about a weird Exception on Nov 14, and you told me that I am
    using Runtime.exec to start an external process, and that process is crashing.
    I am a green-hand on Weblogic, and I am trying to enhancing a project developped
    by another person, so I am not familiar with some concepts yet.
    Could you please give me some simple explanation about Runtime.exec and external
    process?
    I found two methods that uses "Runtime" from two classes as following, could you
    help me to see whether or not there is something wrong with the usage of Runtime?
    Thank you very much.
    private int runShellCommand(String command) {
    int exitVal = -1;
    try {
    File runDir = new File(runDirectory);
    String[] env = new String[0];
    Runtime rt = Runtime.getRuntime();
                   double start = System.currentTimeMillis();
    Process proc = rt.exec(command, env, runDir);
    // Capture output in separate thread
    ThreadedStreamReader error = new ThreadedStreamReader(proc.getErrorStream(),
    "ERROR");
    ThreadedStreamReader output = new ThreadedStreamReader(proc.getInputStream(),
    "OUTPUT");
    error.start();
    output.start();
    exitVal = proc.waitFor();
    if (logger.isDebugEnabled()) {
         double runtime = (System.currentTimeMillis() - start) / 1000.0;
         logger.info("run " + runId + " " + command + " finished in " + runtime
    + " seconds");
    } catch (IOException e) {
    logger.fatal("DOE-2 failed \n" + e.getMessage());
    } catch (InterruptedException e) {
    e.printStackTrace();
    return exitVal;
    public static void main(String[] args) throws Exception, InterruptedException
    final Doe2MessageServer server = new Doe2MessageServer();
    while(!connected) {
    Thread.sleep(1000);
    logger.info("Attempting to start JMS service ...");
                   try {
              server.init();
                   } catch (Exception ex) {
    // shutdown hook to close JMS connection
    Runtime.getRuntime().addShutdownHook(
    new Thread() {
    public void run() {
    server.finalize();
    server.receiveMessage();

  • Strange problem when a c++ program is triggered by Runtime.exec()

    I am working in linux system. I have 2 programs:
    1. one is a c++ program e.g. AAA. In this program, i use "system("gcc ...")" to call gcc to do some internal processing
    2. the other is a java program BBB. In this program, i use Runtime.exec("AAA") to run program AAA.
    case 1
    if I run c++ program AAA directly, everything goes well, gcc call via "system" is successful.
    case 2
    if I run java program BBB to trigger AAA indirectly, the AAA can be executed, but the system call (gcc call inside AAA) is failed.
    so, what is wrong? any hints? what is the solution to make case #2 work? I just want to use BBB to trigger AAA, and the system call should also be successful.
    thanks in advance for your help!

    "...but the system call (gcc call inside AAA) is failed."
    Isn't terribly descriptive, but I'm guessing that it complains it can't find gcc?
    If that's the case then it's because the call to Runtime.exec() runs the code in a shell with no idea where anything is, whereas when you run the C++ code straight it is running in the shell you kicked it off in. Something along those lines anyway.
    Someone else'll be able to tell you how to get it to work. I'm sure I've seen this sort of problem here several times.

Maybe you are looking for

  • Down payment- vendors

    Hi gurus In case of downpayment for venodrs, at the time making payment f-48 the Special G/l indicator in in required status how can i make that Special G/L indicators icon to optional status. can you please tell me............. Thanks Sreenivasulu.P

  • BI Business Content Installation

    Hi Experts I had BI-7 IDES installed in my system, i seee no objects are been installed from business Content. Can any one please suggest how to proced to install the objects like infoarea, infoobjects, Data targets... which one first and then goes n

  • When i update my iphone 4s in itunes, it shows error 1. What can i do now?

    When i update my iphone 4s in itunes, it shows "error 1". What can i do now?

  • Invalid EFI file path when dual boot

    I'm trying to dual boot arch linux with windows 7. I have windows 7 and my plan for partition is sda 4:0 128g <- SSD ├─sda1 4:1 0 70g 0 part <- windows 7 already installed. ├─sda2 4:2 0 4g 0 part <- /swap ├─sda3 4:3 0 500m 0 part <- /boot ├─sda4 4:4

  • Unexpected Error when submitting Claim Code

    Hi there. I have tried all instructions on HP site to link printer for HP ePrint. However, when submitting Claim Code I get the message 'Unexpected Error'. Can someone help?.Thank you.