Runtime.exec() process executes too fast!

I'm trying to pipe some data into an external process via Process.getOutputStream(). However, this program can operate with or without reading from stdin.
Between the time I run Runtime.exec() and the time I can call Process.getOutputStream(), the process has already decided there's no data coming from stdin and exits.
Is there any way to give a process stdin data before exec'ing?
thanks in advance
Ken

too fast? never heard that complaint before.
Well, either it waits for something on stdin or not. If it determines that there's no stdin that fast, how does it ever wait, cuz no user would type faster then the JVM would get the ouputstream? I mean, if you run it on the command line manually, does it sit and wait? Cuz if not, it's not taking stdin at all. Or are you referring to arguments from the command-line, in which case you need to pass them in the Runtime.exec() method first.

Similar Messages

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

  • Best way to close a Runtime.exec() process and how to handle closing it?

    I have multiple Runtime.exec() Processes running and am wondering what the best way it is to close them and take care of closing the resources. I see that Process.destroy() seems to be the way to terminate the Process - is finalize() the best way to close anything in that Process?
    Thanks

    I was involved with your other thread, so I think I know what you are trying to do.
    All Dr's answers are correct.
    Now you have a program A written by you that does Runtime.exec() of multiple instances
    of another program B written by you. You want A to somehow tell B to exit.
    You must use some kind of Inter Process Communication. If this is the only interraction
    between the two programs I can suggest two options. If you anticipate more
    interraction, you may want to look at other means (RMI, for instance, which was proposed
    by EJP in the other thread for starting B, is also useful in exchanging info).
    Solution 1:
    Start a thread in B and read stdin. A will write to stdin a command, such as QUIT.
    When B reads it, it does System.exit().
    Solution 2:
    Start a SocketServer in B that accepts connections on a separate thread.
    When A wants B to exit, it connects to it and writes a command such as QUIT.
    When B reads it, it does System.exit().
    You may note that QUIT is not the only command you can send from A to B, in case you will need more.
    Edited by: baftos on Nov 5, 2007 2:15 PM

  • Using Runtime.exec to execute a C++ executable

    Hello,
    I would like to know if it possible to execute a C++ executable using Runtime.exec() and wait for it to complete and how do I read back the output file created by the C++ executable into the Java Code?
    TIA.
    RHP

    When I execute the code with Runtime.exec(), and read
    from the Process's inputStream I am ablt to view the
    cout from the C++ code. But the output file that has
    to be created by the C++ code is not created,Then this is maybe an error in the C++ code? Maybe you don't have permissions to create that file where you want to.
    where
    would the output from the C++ code go to when I use a
    ofstream in my C++ code andIf you create the file stream in C++ with an absolute file name then the output goes into that file. If it's a relative file name, then the basis is most likely the current working directory (found in the system property "user.dir" if you used one of Runtime's methods without the File argument, otherwise it's the directory you provide.
    How do I read both streams
    from the Java Code?You create an FileInputStream and - if you want to read character instead of binary data - on top of that an InputStreamReader. You might add a BufferedReader on top of that if you want to read line by line.
    does that answer your questions?
    robert

  • Runtime.exec() process output

    I am having strange problems with the output from a program I am executing with Runtime.exec(). This program takes voice input, and generates text output on the commandline. For some reason, I do not see any of the output until the program exits, then everything is displayed. My code is below, any help would be greatly appreciated!
    Thanks,
    Deena
    import java.io.*;
    import java.util.*;
    //Reads and prints the output streams from an executing process
    class ProcessStream extends Thread{
         InputStream is;
         String type;
         ProcessStream(InputStream is, String type){
         this.is = is;
         this.type = type;     //type of output stream, e.g. stdout or stderr
         public void run(){
         try{
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line=null;
                   //read and display the output stream of an executing process
              while ((line = br.readLine()) != null){
              System.out.println(type + ">" + line);
         } catch (IOException ioe){
         System.err.println(ioe);
    //Interface to TalkBack.exe
    public class JTalkBack{
         public static void main(String[] args){
         try{
              String arg="TalkBack.exe -noTTS -noReplay";     //program to execute
              //arguments to program
              for(int i=0; i<args.length; i++){
                   arg+=" "+args;
              //execute the program and get an object representing the process
              Process p=Runtime.getRuntime().exec(arg);
              //create stream processors for stdout and stderr of the process
              ProcessStream error = new ProcessStream(p.getErrorStream(), "ERROR");
              ProcessStream output = new ProcessStream(p.getInputStream(), "OUTPUT");
              //start the stream processors
              error.start();
              output.start();
              //wait for the process to finish and get its exit value
              int exitVal = p.waitFor();
         System.out.println("ExitValue: " + exitVal);
         catch (Throwable t){
         System.err.println(t);

    I have something similar and it works. The only difference is that I:
    1. used a BufferedInputStream instead of the BufferedReader, which means bis.available() and bis.read(buffer) were used instead of .readLine(bis)
    2. Didn't print to stdout, but instead fired a proprietary MessageEvent with the string in it to all MessageListeners (good for use with java.util.logging)
    3. Didn't (yet) put the input streams in different threads.
    Maybe it is related to the fact that you are printing directly back to the System.out again? Does each process in Java get its very own standard out? I don't know.
    It's ugly and convoluted, but maybe a snippet of my code will help...
    (in run)
    Thread myThread = Thread.currentThread();
      try {
        proc = r.exec("my_secret_process.exe -arg arg");
        is = new BufferedInputStream(proc.getInputStream());
        while (thread == myThread) {
          int iRead = 0; //how many bytes did we read?
          //message stream check
          if(is.available() > 0) {
            iRead = is.read(buf);
            msg = "\n"+new String(buf, 0, iRead);
            this.fireMessageArrived(new MessageEvent(this, msg));
         } //end while
       } catch(Exception e) {
          System.out.println("Argh.  Barf.");
      Tarabyte :)

  • Runtime.exec not executing the command !

    Hi all,
    I'm connecting to Progress Db thru JDBC trying to execute a stored procedure
    which has a statement
    Runtime.exec("ksh -c aa") where aa is aunix script which i'm trying to run from java snippet .
    when i run this code as a seperate java program it executes the script
    "aa" but thru JDBC connection it does not execute the command
    what could be the reason ???
    thanx in advance,
    Nagu.

    Hi Rick,
    "aa" is the shell script which is lying in the user DIR .
    It is returning a non-zero value. what kind of permissions be there for to execute the Shell command?
    Regards,
    Nagarathna.

  • Using Runtime.exec to execute Java.exe

    I am trying to use Runtime.exec to spawn a thread that runs java.exe, but havn't had any luck. I have two versions of code, the first one works (example 1), but I want to eliminate the use of "cmd /c" to keep system independance. The second example (example 2) does not work. Both versions work if invoked from the command line. I'm running Win2000. Any Ideas?
    Example 1:
    aProcess = aRuntime.exec("cmd /c java.exe
    -cp "<MyClassPathHere>" <arg1> <arg2> <arg3> <arg4> <arg5>");
    Example 2:
    aProcess = aRuntime.exec("java.exe
    -cp "MyClassPathHere" <arg1> <arg2> <arg3> <arg4> <arg5>");

    I think you mix two concepts: "threads" and "processes". A "thread" is a thread of execution inside the VM, but you want to actually start a new VM in a new process, which is an OS level thing, right?
    I've tried Idea 2 also, same result: works if
    i specify cmd c/, doesn't if I don't.It should work if java.exe is in your path... are you taking care of the standard streams of your process?

  • BUG? Can't exit JVM until native Runtime.exec() process exited.

    Hi,
    Before reporting this as a bug I wanted to hear some opinion.
    The problem :
    I start a win32 native appllication and then I have to close the VM and leaving the process running.
    But inpite any Runtime.exit() or Runtime.halt() call, the vm won't not exit until the proces ends.
    Having seen that there could be some issue with the output stream of the process and the VM I tried to redirect it to a file. But still the same.
    Any opinion?
    Dikran

    You have something else going on.
    The following code exits and leaves the app running...
        public class TTest
            public static void main(String[] args) throws Exception
            Runtime.getRuntime().exec("notepad");
        }

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • 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

  • Process proc=runtime.exec("sh","-c","//home//usr//mkdir abcd") not working

    my servlet calling the above line is not executing to make a directory
    "abcd" at specified location. i am using Mandrake Linux and Tomcat... can anybody expalin the error.

    Hi raghutv,
    I also have this error
    I use Tomcat 4.0 and Window Me
    Do u think that the problem is "Window OS" or Tomcat Setting
    I have a problem. I want to complie the other Java Program "hi.java" using servlet.
    I am compiling the servlet code succesfully, but the web page can't display anything.
    The real path of "hi.java" is in the
    D:\Program Files\Apache Tomcat 4.0\FYP\WEB-INF\classes\hi.java
    This is my servlet code..............pls help.............thx!
    /*********************** Hello.java *********************/
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Hello extends HttpServlet
    public void service(HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException, IOException
    try {
    String path = getServletContext().getRealPath("\\WEB-INF\\classes\\hi.java");
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("javac.exe " + path);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    PrintWriter com_out = res.getWriter();
    com_out.println("<pre>");
    String line = null;
    while((line = br.readLine()) != null){
    com_out.println(line);
    //String[] cmd = { "ping.exe", "time.nist.gov" }; // Command and argument
    //String[] cmd = { "javac.exe","hi.java"}; // Command and argument
    //Process process = Runtime.getRuntime().exec(cmd); // Execute command
    //Process process = Runtime.exec(cmd); // Execute command
    //process.waitFor(); // Wait until process has terminated
    catch (Exception e) {
    System.err.println(e);

  • Runtime.exec does not execute my program, but executes "ls"

    I am trying to run an exe from a Java program.
    The program that I want to run is an output of a gcc -o ICDDATA ICDdata.c
    Now when I use the Runtime.exec() and execute "ls", "cat" it is working fine without any errors.
    But when i try to give the file(ICDDATA) that was created with the gcc, it generates an error code of "11" or "10" and exits the process.
    Could anyone please let me know the reason why this is happenig and suggest and appropiate solution for this.

    When I give ICDDATA at the prompt, it is executing perfectly fine.
    But only when it is run inside the Java program its giving the error code 10.
    Here is the source code:
    ======================================
    public class InvokeInterface {
         This method takes two parameters and accordingly invokes one of the
         interface (ICD / Value).
         @Input : String, String
         @Return : void
         static void executeInterface(String processName, String debugOption)
         throws java.io.IOException     {
              String commandToExecute=". / ";
                   // The command that has to be passed to the Shell.
              if(processName.equals("ICD"))
                   commandToExecute="ICDDataRefresh";
              if(processName.equals("VALUE"))
                   commandToExecute="ValueDataRefersh";
              commandToExecute += " "+debugOption;
              System.out.println("..."+commandToExecute);
              Runtime runtime = Runtime.getRuntime();
              Process proc = runtime.exec(commandToExecute);
                   try {
                        if (proc.waitFor() != 0) {
                        System.err.println("exit value = " +
                        proc.exitValue());
              catch (InterruptedException e) {
                   System.err.println(e);
    ==========
    Thanks in Advance
    Ram

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

  • Don't redirect output or Runtime.exec()

    Hello, I am using Runtime.exec() to execute a .bat file on a windows xp machine. I am able to read the output within the java app just fine. The problem is that I don't want the output to be redirected to a java stream as the default behavior of Runtime.exec() enforces. Is there anyway to run a .bat file and have the output stay in the DOS window that appears?

    Thanks for the input so far. Here is more detail. I have to execute the bat file. No way around that one. I tried getting no window to pop up but the only solution I found to this was to create a shortcut and launch the process with a minimized window. Not to keen on this solution as it isn't very elegant. Plus it would be very very bad if the window was closed in the middle of execution. If anybody knows of a better way not to have the window show up I would like to hear it.
    So now I am stuck with a blank DOS window. I figure the next best thing is to just use the window and have the output that normally shows up there to actually show up there when launched from a java process. This way hopefully the user realizes something is running in the window and they shouldn't close it.
    You would think java would have some way to a launch a process and forget about it.

  • 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

Maybe you are looking for

  • After upgrading to Leopard, I can't access iPhoto

    I get a window saying "You cannot use this version of the application iPhoto with this version of Mac OS X." When I try to download a newer version, a get a window saying something about how it can't be found in applications. All my pix are in there.

  • Quicktimes from AVID into FCP

    I exported a final piece from AVID Adrenaline as an uncompressed Quicktime. I took that QT to my Mac (G5, OS 10.4.1, FCP 5.1.4), and imported it into FCP. The resulting clip has audio, but the video is completely white. The QT also does not play on Q

  • Post Balance Sheet Adjustment Tx. F.5E

    hi, Anyone, help me in this regard - after doing foreign currency valuation(Tx. F.05) reverse, i did calculate balance sheet adjustment(i.e., Tx. F.5D) and when i am trying to do the Post balance sheet adjustment(Tx. F.5E) no values are posted and it

  • Maximum Line Items

    Dear Experts, I have an issue,When I am running the daily consumption file through a note pad to SAP(As we have another system from where the datas are being derived) by a  Z report(developed),the error is showing maximum line items in FI has reached

  • Object class for AUSP table

    Hi Experts, Iam working on change pointers for the Material. In BD52 transaction iam able to enter some fieds for the material. But i need to enter Material Classication, and i found AUSP-ATWRT field. Now, i want to pass this table & field into BD52