Java.lang.Process.exec()

I have read a article about the "java.lang.Process.exec()" (url:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)
Having some questions with the example in it.
The example code:
import java.util.*;
import java.io.*;
public class BadExecJavac
    public static void main(String args[])
        try
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("javac");
            //int exitVal = proc.exitValue();
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t)
            t.printStackTrace();
}The process can run but never complete.
Why? Just because when invoke the javac.exe without any argument,it will product a set of usage statements that describe how to run the program and the meaning of all the available program options.So the process is in deadlock.
The question is, when i change the exec("javac") to exec("javac a.java"), in which the "a.java" is not exist, so the jvm should product error:
error: cannot read: a.java
1 error
But after i changed the code and run the class, at this time the process can run and complete.
The two codes both product some statements,but why the first one never complete,but the second did. Why?

import java.util.*;
import java.io.*;
public class A
    public static void main(String args[])
        try
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("javac");
            InputStream is = proc.getErrorStream();
            int i=0;
            while ((i = is.read()) != -1)
                System.out.print((char)i);
            // int exitVal = proc.exitValue();
            // int exitVal = proc.waitFor();
            // System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t)
            t.printStackTrace();
}usng this modification, i could see some error messages.
because exec(cmd) executes the command in a separate process, it will not display the results on the current console. If you want see the results, you should use getInputStream() and getErrorStream().
good luch ^^

Similar Messages

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         public void run() {
              try {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ((line = br.readLine()) != null) {
                        System.out.println(type + ">" + line);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Get complete output from java.lang.Process

    How do I get the complete output from java.lang.Process?
    By the time I've started reading from Process.getInputStream() the process has already terminated...

    I solved the problem:
    private int exec(String pArguments[], OutputStream pOut, OutputStream pErr) throws IOException {
         class ProcessOutputPrinter implements Runnable {
              private InputStream ivIn;
              private OutputStream ivOut;
              public ProcessOutputPrinter(InputStream pIn, OutputStream pOut) {
                   ivIn = pIn;
                   ivOut = pOut;
              public void run() {
                   try {
                        for(int tByte; (tByte = ivIn.read()) != -1; ) {
                             ivOut.write(tByte);
                        ivOut.flush();
                   catch(IOException e) {
                        e.printStackTrace();
         // Start process
         Process tProcess = Runtime.getRuntime().exec(pArguments);
         // Create out printer
         Thread tOutPrinter = new Thread(new ProcessOutputPrinter(tProcess.getInputStream(), pOut), "NamingAdmin out-printer");
         tOutPrinter.start();
         // Create err printer
         Thread tErrPrinter = new Thread(new ProcessOutputPrinter(tProcess.getErrorStream(), pErr), "NamingAdmin err-printer");
         tErrPrinter.start();
         // Wait for process and printers to finish
         try {
              tProcess.waitFor();
              tOutPrinter.join();
              tErrPrinter.join();
         catch(InterruptedException e) {
         // return process exit value
         return tProcess.exitValue();

  • Java.lang.Process output stream problem

    Hi, I have a program that starts a process (java.lang.Process) using the java.lang.Runtime.exec() and it attemtps to interface with it using the provieded io streams. I have both the output and error streams being handled on their own threads and I have a hashmap of output lines/command pairs that are checked so that when the process outputs certain lines to the console it feed the proper input into the process. My problem is that when I feed the input into the process it dosen't respond to it almost like the user hasn't pressed enter, The process hangs. I have tried using /n /r and permutations thereof but nothing works. The thread does read the lines from the process and does output to the process from what i can gather. Can you help me!
    here is some of the code..
    public void run() {
    try {
         //the process's output
         InputStreamReader isrOutput = new InputStreamReader(inOutput);
         //the process's input(our output)
         PrintWriter pw = new PrintWriter(outInput);
         String line = null;
         while(true){
              if(brOutput.ready()){
                   line = "";
                   while(brOutput.ready())
         line+=(char)brOutput.read();
                   System.out.print(line);
                   if(commands.containsKey(line)){
         pw.println((String)commands.get(line));
         System.out.println((String)commands.get(line));;
    } catch (IOException ioe) {
              ioe.printStackTrace();
    }Thanks

    Oops.. i forgot to flush my PrintWriter /blushing......... Thanks

  • Java.lang.process.execute()

    Java.lang.process.execute() is throwing an exception with string �Cannot allocate memory� ...
    what is the cause of this exception and give me the solution
    plz help
    Nilesh

    882590 wrote:
    Is it possible to use the java.lang.ProcessBuilder to execute a Java process pointing it to jvm.dll instead of java.exe? I'm using the JavaFX self contained application packaging and it creates a runtime/jre/bin directory that contains jvm.dll, but not java.exe.I don't get the line of questioning of this thread. If you're using the JavaFX stuff the answer must lie in the JavaFX documentation. It seems to indicate that it generates an executable of its own which will likely wrap the jvm DLL, so you should be invoking the generated executable in ProcessBuilder.
    http://docs.oracle.com/javafx/2/deployment/self-contained-packaging.htm

  • Java.lang.Process input stream waiting until process is complete to print

    I have tried to simplify this problem as much as possible. Basically, I have a java.lang.Process which executes a simple C program.
    test.c
    #include <stdio.h>
    #include <unistd.h>
    int main()
      printf("foo\n");
      sleep(2);
      printf("bar\n");
    ...The process has an input stream and error stream handler each on a separate thread. I have tried both buffered and unbuffered (BufferedReader, BufferedInputStream, InputStreamReader...) stream handlers. Both produce the same problem of waiting until the process has exited to receive anything from the process's streams.
    The only time this does not happen is when I call fflush(stdout); after each printf(). This can't be a solution because the real application calls a massive C application which would require thousands of fflush()'s to be added. What is causing this to happen? This doesn't happen when the C program is executed from the shell. Is there a way the InputStream can be forced to extract from the stream?

    hi.....
    I have closed the output stream of the process as you told me to do...
    The hitch is that, if my program contains only printf() statements,it works fine
    as soon as scanf() statement is encountered within the C code,it is totally neglected,and the output comes as if no scanf() statement existed in the C code.
    Consequently the thread doesnt wait for input which was bound for scanf() from the thread
    the code...
        public void run()
         try
             PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
             BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            socket.getInputStream()));
             try
                     Process p;
              p=new ProcessBuilder("./a.out").start();
                     PrintWriter exOut=null;
                     BufferedReader exIn=null;
              exOut = new PrintWriter(p.getOutputStream(),true);
              exIn = new BufferedReader(
                           new InputStreamReader(
                           p.getInputStream()));
                  //String inputLine="", outputLine="";        
                  String str="";
                     int c;          
                  while(true)                   
                        //System.out.println("In While");
                  str="";exOut.close();                  
                        while((c=exIn.read())!=-1)
                                 str=str+(char)(c);
                                    System.out.print(str);
                        str=str+(char)(0);
                        System.out.print(str+"outside");
                        out.print(str);
                        sleep(100);
                        try
                            int x=p.exitValue();
                              out.print(str);
                   System.out.print("Bye 1");
                            String str1="Bye"+(char)(0);
                   out.println(str1);              
                   break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                        //str=str+((char)-1);
                        //System.out.print(str+"Control reaches here too");
                        str="";
                        exOut = new PrintWriter(p.getOutputStream(),true);//I have tried to run the program without this also but the effect is the same
                        while((c=in.read())!=-1)
                            str=str+(char)(c);                                    
                        if(str.contentEquals(""))
                                System.out.print("Bye 2");
                                String str1="Bye"+(char)(0);
                                out.println(str1); 
                                p.destroy();
                                exOut.close();
                                exIn.close();
                                out.close();
                                in.close();        
                                socket.close();
                                break;
                        //str=str+(char)(0);
                  exOut.print(str);
                        try
                            int x=p.exitValue();
                            System.out.print("Bye 3");
                            String str1="Bye"+(char)(0);
                   out.println(str1);
                            break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                  /*while ((inputLine = in.readLine()) != null)
                        exOut.println(inputLine);
                        outputLine=exIn.readLine();
                        //outputLine=inputLine;
                        //out.println(outputLine);}*/                   
             exOut.close();
             exIn.close();
             catch(IOException e)
                  System.err.println("Accept failed."+e);
             out.close();
             in.close();        
             socket.close();
         catch (Exception e)
             e.printStackTrace();
    }

  • Problem with starting a sqlplus-process via java.lang.Process

    Hi,
    I want to start a sqlplus-Process from a java-application via java.lang.Process. Works great with XP. On a W2K-Machine, the process is started (I can see it in the Taskmanager), but it doesn't connect to the db - the OS-process hangs, also the java-application which invoked the process.
    If I start a sqlplusw.exe-Process instead of sqlplus.exe, it works as well.
    Does anybody know what's going wrong ?
    I'm using java 1.5.0_11 and Oracle Database 10g Enterprise Edition Release 10.2.0.3.0
    Thanks in advance
    Jens

    java.lang.Process can be used to perform an OS Shell to launch specific tasks. But why are you interested in specifically launching sqlplus from here?
    ~ Madrid
    http://hrivera99.blogspot.com/

  • Problwm with java.lang.Process

    I am using java.lang.Process to read the output of a command, it works fine with one word commands such as "ls", but a command with a pipe and and arguments returns no output, for example "who | grep root".
    Any ideas!

    for example "who | grep root".
    Any ideas! Probably because you really should have nothing returned. Try to give the output of the first command as an input to the second one but not through a pipe; use java.lang.Process twice.

  • About java.lang.Process class?

    hi, i am executing one batch file (it contains 2 executable statements) through java.lang.Runtime class exec method like this..Process p1=r.exec("cmd /K start .\\Skeletons\\reports\\FormatFiles\\"+strDTab+".bat");.. i want to get the output of this process is it success, failure or suspect?. how to use the waitFor() method of Process class in this situation?. and also the execution of the batch program will give some status (if fail it will throw some exception), i want to catch the status. depending on the status i will decide proceed to further statements or not?..

    You use waitFor() by calling it on the process you get back from the exec()
    If you want examples use google to find them.

  • Java.lang - process builder

    I want to execute the following command inside my java program
    rep_cmd [file1] -text [file2]
    The above command belongs to an application installed on my PC.
    The above command when executed in the command prompt works fine.
    but it does not work inside my java program
    here is my code:
    public class ProcBuild
    public static void main(String args[]) throws IOException, InterruptedException
    String cmdLine="cmd /c rep_cmd log.wgl -text log1.txt";
    ProcessBuilder pr=new ProcessBuilder(cmdLine);
    pr.start();
    and here is my error message with output:
    run:
    Exception in thread "main" java.io.IOException: Cannot run program "cmd /c "rep_cmd log.wgl" -text "log1.txt"": CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
         at ProcBuild.main(ProcBuild.java:23)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(ProcessImpl.java:188)
         at java.lang.ProcessImpl.start(ProcessImpl.java:132)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
         ... 1 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    Edited by: user13286843 on Jan 20, 2012 9:20 AM

    >
    Exception in thread "main" java.io.IOException: Cannot run program "cmd /c "rep_cmd log.wgl" -text "log1.txt"":
    >
    You are passing the entire command as one String and the string is being interpreted as the name of the program and no arguments.
    See the Javadocs for ProcessBuilder. It has an example that shows how to pass the cmd, and each argument as separate Strings.
    Get the Javadoc example working first and then substitute your command and arguments.
    Starting a new process which uses the default working directory and environment is easy:
    Process p = new ProcessBuilder("myCommand", "myArg").start();
    Here is an example that starts a process with a modified working directory and environment:
    ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
    Map<String, String> env = pb.environment();
    env.put("VAR1", "myValue");
    env.remove("OTHERVAR");
    env.put("VAR2", env.get("VAR1") + "suffix");
    pb.directory(new File("myDir"));
    Process p = pb.start();

  • Linux, java.lang.Process.getOutputStream() funniness

    Hi,
    I'm using RedHat 7.1, and Sun JDK 1.3.0_02 (on Intel).
    From my Java app, I'm trying to launch another process, and redirect my
    console in/out to the slave process's in/out.
    After launching the process (using Runtime.exec), I launch three
    background threads:
    1. Monitor the slave process's getInputStream and write all incoming
    bytes to my System.out
    2. Monitor the slave process's getErrorStream and write all incoming
    bytes to my System.out
    3. Monitor my System.in and write all incoming bytes to the slave
    process's getOutputStream
    The funniness I'm experiencing is in step 3 -- it seems that I have to
    press each keystroke TWICE, for it to register into the slave process.
    For example, as a test, I am launching "lynx http://www.cnn.com", and
    the lynx options "H" and "O" I have to press twice (H-H or O-O) to get
    the appropriate screen to pop up. In fact, the first keystroke I enter
    doesn't matter; it's as if every other keystroke is looked at.
    Here is my code for thread #3:
    // -------- Begin code fragment
    // Start an input thread
    Thread inThread = new Thread() {
       public void run() {
          OutputStream out = slaveProcess.getOutputStream();
          byte[] buffer = new byte[1024];
          int len;
          while (true) {
             try {
                len = System.in.read(buffer);
                if (len == -1) break;
                //System.out.println("Bytes read from keyboard: " + len);
                out.write(buffer, 0, len);
                out.flush();
             } catch (Exception e) {
                break;
          System.out.println("inThread exiting");
    inThread.start();
    // -------- end code fragment In reference to some older JVM bugs, I've tried inserting
    Thread.currentThread().sleep(1) at various points (in case there is a
    scheduler problem), but to no avail.
    Any help would be appreciated!
    Thank you,
    Bryan

    I would test it buy using three FileIn/OutputStreams
    instead of Syatem.in/out/err and if it worked at that
    point it would be the synchronization/blocking problem.
    Because I have used Process.getInputStream on linux on
    several occasions and never anything like you are
    talking about happened.

  • Java.lang.Process  - detecting process termination asynchronously

    Hi All,
    I was wondering if there is anyway to know when a Process (run with Runtime.exec()) has terminated without dedicating a thread per Process and using waitFor().
    The reason I want this is that I have an application running many such processes concurrently, and I wouldn't want to dedicate a thread for each process to detect its termination.
    What I would REALLY like is something like the asynchronous IO 'select' method so that a single thread can block until one of a set of processes terminates.
    Polling would not be as good, but also a viable alternative. However, the only way I could see is calling exitValue() periodically on all Process objects - this would mean getting IllegalThreadStateExceptions thrown galore, as long as the process doesn't terminate. This is both ugly and inefficient (makes the penalty for polling even worse - we generate an exception for each non-terminated process polled...).
    Does anyone have any tips I can use to implement some sort of solution?
    Thanks,
    Ophir.

    >
    What's the requirement for detecting the completed
    processes? I'm not really sure why the Thread per
    process version wasn't acceptable. How many processes
    are there?
    Well... it's an application server, and I'm providing a generic capability. Theoretically, it could be hundreds of processes.
    Also, did you make sure that the Process Object is
    indeed not collectable until the process is complete?I have to say I was pretty skeptical about this myself... ;)
    I have made the test as well as I know: I ran a long running process, and then terminated it with 'kill'.
    I also ran 'sleep 60' to see what happens on normal termination.
    I saw nothing added to the queue while the process was up, and immediate enqueuing after process termination.
    I guess there's no way of making ABSOLUTELY sure this works but if it didn't become collectable 20 consecutive times when up, and became collectable immediately when terminated, that's pretty strong circumstancial evidence...
    Still I just wish there was a neater, tighter solution (though, using your hack, I'm going to get a lot of admiration from some of the people around here - they don't need to know where I got it...).

  • Java.lang.Runtime.exec() again

    try{
    Process registryProcess = null;
    Runtime r = Runtime.getRuntime();
    String[] cmdArray = {"F:\\windump", ">>new_res.txt"};
    registryProcess = r.exec(cmdArray);
    }catch(Exception ex){
    System.out.println("Exception Caught: " + ex.getMessage());
    ** Have also tried speicfying the command and the parameters all in the one string like so :
    String cmd = "F:\\windump >>F:\\new_res.txt";
    registryProcess = r.exec(cmd);

    try
    String cmd = "cmd /c F:\\windump >> F:\\new_res.txt";
    registryProcess = r.exec(cmd);

  • [java.lang.Process] Howto simulate ENTER ?

    Hi there!
    I need to control an interactive command-line tool from java (smbclient) and for this task I use Process with getOutputStream().
    However I want to send commands to the native-program like: Process.getOutputStream.write("exit\n".getBytes()) but it simply does not work :-(
    I think the native programs does not recognize the "\n" as <ENTER> .
    Any ideas howto solve this problem?
    Thanks you in advance, Clemens Eisserer

    Well, thanks for the tips!
    Since I am running Unix '\n' shoulb we enough, but thanks for remembering me g
    Well, I actually forgot to flush the output-Stream. Nobody is perfect ;-)
    Thanks again, lg Clemens

  • Java.lang.Runtime.exec()

    When using the exec method I cannot get it to run the specified application when I try to use the Runtime.execString[] cmdArray)
    The application I am running is windump, it runs ok when I specify it in the Runtime.exec(String cmd) method.
    I need to use the Runtime.exec(String[] cmdArray) option as I need to specify parameters as part of my project. To be exact I need to tell it to output to a text file.
    I can do this when running windump from the command prompt, thus cannot understand whty it wont work when I specify the same option from Runtime.exec(..)
    Any ideas how to overcome this?
    thanks Conor

    This works for me on WindowsNT:
    try {
         Runtime.getRuntime().exec("cmd.exe /c dir>dirtest.txt");
    catch (Exception e) {}
    [/code}
    Mark

Maybe you are looking for