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

Similar Messages

  • 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 output lost when executing ftp.

    I'm writing application, which can execute command line scripts.
    I'm executing Runtime.exec("cmd") and then writing commands into output stream. I'm continously reading from input and error stream, so that's not the case.
    Everything goes fine while I'm executing simple commands, like: dir, cd.
    The problem begins when I try to execute more sophisticated commands, like ftp.
    Here is the scenario:
    ftp server_nameFtp asks for user name
    userAfter providing user name, the output is lost. There are no more characters in InputStream ever. The application doesn't hangs, because ftp actually performs next commands (password, cd, get file). It is just output that isn't shown.
    Is it known problem or am I doing something wrong?
    Please, help.

    I post some code:
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        char[] buf = new char[1000];
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                boolean write = false;
                while (true) {
                     StringBuffer buffer = new StringBuffer();
                     while (br.ready()) {
                          int chars = br.read(buf, 0, 1000);
                          buffer.append(buf, 0 ,chars);
                          write = true;
                     if (write) {
                          System.out.print(type + ">" + buffer.toString());
                          System.out.flush();
                          write = false;
                    try {
                             Thread.sleep(1000);
                        } catch (InterruptedException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    class StreamForward extends Thread
        InputStream is;
        OutputStream os;
        StreamForward(InputStream is, OutputStream os)
            this.is = is;
            this.os = os;
        public void run()
            try
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                OutputStreamWriter wr = new OutputStreamWriter(os);
                String line=null;
                while ( (line = br.readLine()) != null) {
                    wr.write(line+"\n");
                    wr.flush();
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class GoodWindowsExec
        public static void main(String args[])
            try
                String osName = System.getProperty("os.name" );
                String cmd = new String();
                System.out.println("OS: "+osName);
                if( osName.equals( "Windows NT" ) || osName.equals("Windows XP"))
                    cmd = "cmd.exe" ;
                else if( osName.equals( "Windows 95" ) )
                    cmd = "command.com" ;
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR");           
                // any output?
                StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT");
                StreamForward forward = new
                     StreamForward(System.in, proc.getOutputStream());
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                forward.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    }This is example code, which demonstrate this problem.
    It creates new cmd process and forwards to it standard input. Process output and error streams are displayed on standard output.
    Basically you can execute dos commands by entering them from keyboard.
    Try:
    dir
    cd something
    etc.
    Now, to show a problem try:
    ftp your_favorite_server
    The program should ask for username. Enter username. Nothing is displayed. Notice that ftp is still running and executing commands, but doesn't display any output.
    Any clue, why this is happening?

  • 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

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

  • Runtime.exec() I need to run a command prompt command from java.

    the code i have that doesn't seem to work is:
    String driveloc = System.getProperty("user.dir").substring( 0, 1 );
            String path = jTextFieldPath.getText();
            String path2 = jTextFieldPath.getText().substring(0, jTextFieldPath.getText().length()-3) + "lst";
            String[] cmd = { "cmd.exe", "/" + driveloc, "ASMtools\\AS11 " + path + " -L >" + path2};
            txt_mf.append( cmd[3] );
            try {
                Process np = Runtime.getRuntime().exec( cmd );
            catch( java.io.IOException ioe) {
                //error
            }jTextFieldPath.getText() contains the path of the file saved by my program.
    the line of code i am trying to run is:
    AS11 FILE1 -L FILE2this line compiles the asm file and converts it to a lst creating an s19 file in the process. AS11 is an exe that aids the command prompt much like javac.
    If you could help me figure this out it would be great.
    Thanks in advance,
    -Juke

    String driveloc =
    System.getProperty("user.dir").substring( 0, 1 );
    String[] cmd = { "cmd.exe", "/" + driveloc,
      "ASMtools\\AS11 " + path + " -L >" + path2};Are you sure you want to invoke cmd.exe with the switch /c or /d or whatever depending on System.getProperty("user.dir") ?
    Starts a new instance of the Windows 2000 command interpreter
    CMD [A | /U] [Q] [D] [E:ON | /E:OFF] [F:ON | /F:OFF] [V:ON | /V:OFF]
        [[S] [C | /K] string]
    /C      Carries out the command specified by string and then terminates
    /K      Carries out the command specified by string but remains
    /S      Modifies the treatment of string after /C or /K (see below)
    /Q      Turns echo off
    /D      Disable execution of AutoRun commands from registry (see below)
    /A      Causes the output of internal commands to a pipe or file to be ANSI
    /U      Causes the output of internal commands to a pipe or file to be
            Unicode
    /T:fg   Sets the foreground/background colors (see COLOR /? for more info)
    /E:ON   Enable command extensions (see below)
    /E:OFF  Disable command extensions (see below)
    /F:ON   Enable file and directory name completion characters (see below)
    /F:OFF  Disable file and directory name completion characters (see below)
    /V:ON   Enable delayed environment variable expansion using c as the
            delimiter. For example, /V:ON would allow !var! to expand the
            variable var at execution time.  The var syntax expands variables
            at input time, which is quite a different thing when inside of a FOR
            loop.
    /V:OFF  Disable delayed environment expansion.

  • Certification Validation fails only when executed through Command prompt

    I am developing a testing application using Java which calls multiples services a certain number of times. A few of these services are https protocol and hence require certification validation when the call is established.
    The testing application works fine when i run it on Eclipse but the requirement is to run a .bat file which in turn will call the java class which has some logic and then call the client stub (which i generated on Eclipse using the wsdl)
    The problem is when i try calling the java class from .bat file or command prompt the call fails with the following error :-
    ======== Running SecurityService ================
    16-May-2011 11:40:36 org.apache.axis.utils.JavaUtils isAttachmentSupported
    WARNING: Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart). Attachmen
    t support is disabled.
    AxisFault
    faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
    faultSubcode:
    faultString: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation faile
    d: java.security.cert.CertPathValidatorException: subject/issuer name chaining check failed
    faultActor:
    faultNode:
    faultDetail:
    {http://xml.apache.org/axis/}stackTrace:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorExc
    eption: PKIX path validation failed: java.security.cert.CertPathValidatorException: subject/issuer name chaining check f
    ailed at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
    at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:975)
    at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:123)
    at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
    at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1107)
    at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:186)
    at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
    at org.apache.axis.client.Call.invoke(Call.java:2767)
    at org.apache.axis.client.Call.invoke(Call.java:2443)
    at org.apache.axis.client.Call.invoke(Call.java:2366)
    at org.apache.axis.client.Call.invoke(Call.java:1812)
    at com.telenor.security.server.service.SecurityServerServiceHTTPBindingStub.loginByPasswordForAssertion(T
    elenorSecurityServerServiceHTTPBindingStub.java:812)
    I have made sure that the required certificates are imported into the Java Keystore . What i find confusing is how does Eclipse not have an issue with the certificate validation ?

    JSSE Reference Guide, Customization section.

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

  • External commands in runtime exec

    Im trying to run commands from the Sleuthkit in a java GUI. These commands have no problem running from the konsole as all the paths etc. have been set up, but when I try to run them with the java runtime exec() they wont work. Similarly,i run standard linux commands in this gui aswell and they run without problem.
    Any ideas whats weong?
    Thanks.

    You didn't tell us exactly what you're doing.Its a forensic GUI that runs konsole based commands
    and displays the ouput in a JText areaThat tells us nothing useful. By "exactly what you're doing," I mean the Java code and the command it's exec()ing.
    >
    You didn't tell us what "doesn't work" means.The 'basic' linux commands work fine in the gui, its
    just the sleuthkit ones that wont run or return
    anything when executed using the runtime exec(). Even
    though running these commands in a konsole works
    fine. THis means all paths have been set.
    Any ideas on a different way to run them or should I
    include more than just the command used on the
    konsole?That still doesn't tell us what "doesn't work" means.
    My previous response still applies.

  • Runtime.exec() - how to open new window for new program?

    Hi,
    I have searched through the forums but haven't found an answer to this one yet. I am using runtime.exec() to start up a new java program. At first I thought it wasn't running properly but, after checking task manager, I have discovered that the new program I open runs, it is just completely invisible to me. I am wondering how I can get the new program to run in a command window or something where I can monitor it.
    Thank you for your help,
    Drew

    Thank you all. After trying to figure out why the start command wouldn't work in the runtime.exec() call(not an executable - I am a dolt), I tried putting it in a batch file and it worked perfectly. Thanks for your help,
    Drew

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

  • Runtime.exec() output streams

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

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

  • Runtime.exec() on RedHat Linux

    Guys
    Like many before me, it seems, I've having a nightmare with Runtime.exec() across platforms when executing local files.
    I've gone for the basic but robust strategy of writing the required function to a local file and then executing the file. This has worked fine on Windows NT/2000 and on Solaris. But RedHat Linux doesn't want to know.
    I know my permissions are good to execute. I can create the file then run it at the command line, but then whenever I go to run from within Java I get an exit value of 255.
    An old chestnut, I know. But can anyone offer an help?
    Cheers
    Dom

    Here's a small class & main method that illustrates the problem.
    The output I get is:
    File path: /tmp/Temp26345.sh
    chmod +x exit value: 0
    Executing file: 255
    I can then go into /tmp and run ./Temp26345.sh at the command line and get the "ls" command to run.
    import java.io.*;
    public class FileExecutor
         public static void main( String[] args )
              if( args.length == 0 )
                   System.out.println("Arguments must be given: [filename] [writeable]");
                   return;
              try
                   FileExecutor fe = new FileExecutor();
                   File executable = fe.createFile( args[0] , args[1] );
                   fe.executeFile( executable );
              catch( Throwable t )
                   t.printStackTrace();
         public File createFile( String fileName , String contents )
              throws IOException
              //Create the file.
              File tempFile = File.createTempFile( fileName , ".sh" );
              //Write to the file.
              FileOutputStream fos = new FileOutputStream( tempFile );
              OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" );
              int length = contents.length();
              osw.write( contents , 0 , length );
              osw.flush();
              osw.close();
              fos.close();
              return tempFile;
         public void executeFile( File file )
              throws InterruptedException , IOException
              String filePath = file.getAbsolutePath();
              System.out.println( "File path: " + filePath );
              Runtime runtime = Runtime.getRuntime();
              //Actual system permission.     
              Process process_perm = runtime.exec( "chmod +x " + filePath );
              int exitValue = process_perm.waitFor();
              System.out.println( "chmod +x exit value: " + exitValue );
              //Execute the file.
              Process process_exec = runtime.exec( filePath );
              exitValue = process_exec.waitFor();
              System.out.println( "Executing file: " + exitValue );

Maybe you are looking for