Java Runtime.exec running java problem

Hi, I have a simple server application, which I would like to run in the background. The following line works for me:
Runtime.getRuntime().exec("cmd /c start java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\server.properties");But it displays the cmd window and I am unable to destroy it. So I would like to use
Runtime.getRuntime().exec("java -jar ..\\server\\server.jar -Dlog4j.configuration=file:src\\test\\resources\\log4j.properties -filename src\\test\\resources\\serverIntegration.properties");But it simply doesn't connect to the server. That means, it starts some java process in the background, but my client fails to communicate (i dont know whether the server doesnt respond or the client fails to send the message, but still, with the cmd /c start it works). So why is that?
A related question. How do I end the process? It is a server that "doesn't end". So I have to kill it and I would assume, that running the java only command would be capable to be destroyed, but with the cmd I have no luck there. I have already tried full paths and the overload of exec with String[] params.

Read [_When Runtime.exec() won't_|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
One reason why your server doesn't run is that it might be writing stuff to stdout (a.k.a System.out). And if your process doesn't read the newly created process' stdout, then that other process will block until something is read (which will be never).
Read all of the pages of that article and follow its suggestions.

Similar Messages

  • Where to put files in using runtime.exec(run.exe)?

    I try to use the following program in EJB to call my EXE program in the J2EE server:
    runtime.exec("c:\\j2ee\\public\\exe\\run.exe temp.txt");
    In the execution of mill_turn.exe, it will open several files for read and write.
    So where to put the file temp.txt and other files the run.exe need to read?
    Looks like the J2EE server can not find them?
    Thanks!

    I got it in Java SE1.4.
    File dir=new File("c:\\j2ee\\public_html\\Mill_turn\\exe\\");
    Process proc = rt.exec(cmd,null,dir);Use above codes, I really got the right output from my external program for the first time. But , after that, the output keeps same when I change the filename in the following code:
    cmd="c:\\..\\run.exe temp.prt"
    to
    cmd="c:\\..\\run.exe Abc1.prt" , which must have different output.
    The codes for calling external program are implemented in the SessionBean of J2EE.

  • Runtime.exec() batch file problem

    Hi folks,
    i have a little problem when I want to execute a batch file through java's runtime.exec() method.
    the execution of a very simple batchfile works (for example opening notepad or other stuff), but I have problems with the following batch file (although it's still simple):
    net use s: \\Dd-nt-fs\Dsmp15_files
    set DSCFG=c:\dscfg
    set PSPATH=c:\adproof
    set ora_path=C:\oracle\ora92
    set path=S:\Dsmp_Q4_2004\Bin;%ora_path%\bin;%path%;
    set nd_font=S:\Dsmp_Q4_2004\Fonts
    set nxPS_FONT_DIR=%ND_FONT%
    set PSPATH=c:\adproof
    set PSFORMS=S:\Dsmp_Q4_2004\PsForms\Telenor
    s:
    cd S:\Dsmp_Q4_2004\bin
    S:\Dsmp_Q4_2004\Dsmp_Reports\Telenor\adproof.exe DBUSER=a_user DBPSWD=a_pswd DBSTR=dbstr ADINFO=adinfo.lst TASKID=a_taskid
    my guess is that there is a problem with the setting of environment variables which correspond to the drive s:
    I mannually added the batchfile (line by line) and looked whether it got through to the command which executes the adproof.exe file: for example the below batchfile worked:
    set DSCFG=c:\dscfg
    set PSPATH=c:\adproof
    set ora_path=C:\oracle\ora92
    s:
    cd S:\Dsmp_Q4_2004\bin
    S:\Dsmp_Q4_2004\Dsmp_Reports\Telenor\adproof.exe DBUSER=a_user DBPSWD=a_pswd DBSTR=dbstr ADINFO=adinfo.lst TASKID=a_taskid
    Here is the java code: in which i execute the batch file:
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("net use s: \\\\Dd-nt-fs\\DSMP15_FILES");
    BufferedReader  b = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    while( (line=b.readLine())!=null) {
          System.out.println(line);
    int exitVal = proc.waitFor();
    System.out.println("Exit Value = "  + exitVal);
    String[] cmd = new String[1];
    cmd[0] = "C:\\Documents and Settings\\tikmi\\My Documents\\mysources\\DSMP Prototype\\print\\hallo3.bat";
    // here i declared the needed settings of the environment variable and pass that array to the exec() method                   
    String[] env = new String[8];
    env[0] = "DSCFG=c:\\dscfg";
    env[1] = "ORA_PATH=C:\\oracle\\ora92";
    env[2] = "PSPATH=C:\\Documents and Settings\\tikmi\\My Documents\\mysources\\DSMP Prototype\\print";
    env[3] = "ND_FONT=S:\\Dsmp_Q4_2004\\Fonts";
    env[4] = "nxPS_FONT_DIR=%ND_FONT%";
    env[5] = "PSFORMS=S:\\Dsmp_Q4_2004\\PsForms\\Telenor";
    env[6] = "ND_PATH=S:\\Dsmp_Q4_2004\\resource";
    env[7] = "PATH=S:\\Dsmp_Q4_2004\\Bin;%ORA_PATH%\\BIN;%ND_PATH%;%PATH%;";
    rt  = Runtime.getRuntime();
    proc = rt.exec(cmd, env);
    b = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    while( (line=b.readLine())!=null) {
              System.out.println(line);
    exitVal = proc.waitFor();
    System.out.println("Exit Value = "  + exitVal);Maybe someone else had similar problems or can help me solving that problem.
    Any advice would be very appreciated.
    regards
    mirkolino

    finally I got it working now.
    for those who are interested in the problem, my code that's now working is the following
    Runtime rt = Runtime.getRuntime();
                            Process proc = null;
                            String cmd = "cmd.exe /c c:\\adproof\\hallo3.bat";
                            proc = rt.exec(cmd);
                            InputStream in = proc.getInputStream();
                            BufferedReader br = new BufferedReader ( new InputStreamReader(in));
                            String line;
                            while( (line=br.readLine()) != null) {
                                System.out.println(line);
                            int exit = proc.waitFor();
                            System.out.println();
                            System.out.println("Process exited with: " + exit);the problem was, that i have to handle and read the input stream
    thanks for you help
    greetings from mirkolino

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

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

  • Any problem with Runtime.exec()

    I am required to launch a local exe from an applet. At present I am using AppletContext.showDocument().The problem with this is that in netscape a box is popped up forcing the user to save that exe file. The requirwment is to run it directly without any message being asked.
    A workaround is to use Runtime.exec(), it works, however I have heard that it is not platform independent.
    (1) Is there a better solution than Runtime.exec() ?
    (2) If not could you give me some info on Runtime.exec() and the problems associated with it ?
    (3) Is there a way to use AppletContext.showDocument() without the message being asked ?
    Shikari.

    First of all, Java is platform independent language, and has many security restriction in it's applets.
    so from an applet you can't excute a program using "Runtime.getRuntime().exec()".
    coz. there is security restriction on that.
    for the "AppletContext.showDocument()" this methid is for displaying the specified document on the client browser, so it can't excute a client program.
    if u need to use Runtime.getRuntime().exec() you have to get the client agreement for that.
    see the applet security restriction for more info.

  • Newbie problem with "Runtime exec" "OutputStream"

    I am running an external process (Oracle Sqlplus) from a simple GUI using "Runtime exec". My problem is that I'm only able to retrieve input from the process after the Java output stream is closed. If I don't close the output stream my application does nothing. As soon as I close the output stream the input from the external process is printed to the screen and the external process is killed.
    I want to be able to start the external process once and then send and receive multiple input and output streams to it without having to stop and restart the process. Currently the only way to retrieve input from the process is to close the Java output stream which closes the process.
    Is this possible? Am I doing something wrong?
    I am new to Java so I appreciate your help.
    My code is below. I am running it on Windows 2000 Workstation, Java 1.4.1, Oracle 8.1.7.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class ProcessTest extends JFrame implements ActionListener {
        private JTextArea upperTextArea;
        private JTextArea lowerTextArea;
        private BufferedReader in;
        private BufferedWriter out;
        public ProcessTest() {
            initialiseComponents();
            setBounds(200, 200, 600, 400);
            setVisible(true);
        public void initialiseComponents() {
            Container contentP = getContentPane();
            contentP.setLayout(new BorderLayout());
            upperTextArea = new JTextArea("SELECT SYSDATE FROM DUAL;\n");
            lowerTextArea = new JTextArea();
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  new JScrollPane(upperTextArea),
                                                  new JScrollPane(lowerTextArea));
            splitPane.setDividerLocation(200);                                     
            JPanel buttonPanel = new JPanel();
            JButton runButton = new JButton("Start Process");
            runButton.addActionListener(this);
            JButton outputButton = new JButton("Write Output");
            outputButton.addActionListener(this);
            JButton flushButton = new JButton("Flush Output");
            flushButton.addActionListener(this);
            JButton closeOutputButton = new JButton("Close Output");
            closeOutputButton.addActionListener(this);
            JButton inputButton = new JButton("Read Input");
            inputButton.addActionListener(this);
            buttonPanel.add(runButton);
            buttonPanel.add(outputButton);
            buttonPanel.add(flushButton);
            buttonPanel.add(closeOutputButton);
            buttonPanel.add(inputButton);
            contentP.add(buttonPanel, BorderLayout.NORTH);
            contentP.add(splitPane, BorderLayout.CENTER);
        public void startProcess() {
            try {
                Process process = Runtime.getRuntime().exec("sqlplus -S " +
                                                             "scott/tiger");
                in = new BufferedReader(new InputStreamReader(
                                         process.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(
                                          process.getOutputStream())); 
                System.out.println("Process Started.");                         
            catch(IOException e) {
                e.printStackTrace();
        public void writeOutput() {
            try {
                out.write(upperTextArea.getText().toCharArray());
                System.out.println("Output Write Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void flushOutput() {
            try {
                out.flush();
                System.out.println("Output Flush Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void closeOutput() {
            try {
                out.close();
                System.out.println("Output Close Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void readInput() {
            try {
                lowerTextArea.read(in, lowerTextArea);
                System.out.println("Input Read Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void actionPerformed(ActionEvent e) {
            String action = e.getActionCommand();
            if (action.equalsIgnoreCase("start process")) {
                Thread thread1 = new Thread(){
                    public void run(){
                        startProcess();
                thread1.start();
            else if (action.equalsIgnoreCase("write output")) {
                Thread thread2 = new Thread(){
                    public void run(){
                        writeOutput();
                thread2.start();
            else if (action.equalsIgnoreCase("flush output")) {
                Thread thread3 = new Thread(){
                    public void run(){
                        flushOutput();
                thread3.start();
            else if (action.equalsIgnoreCase("close output")) {
                Thread thread4 = new Thread(){
                    public void run(){
                        closeOutput();
                thread4.start();
            else if (action.equalsIgnoreCase("read input")) {
                Thread thread5 = new Thread(){
                    public void run(){
                    readInput();
                thread5.start();
        public static void main(String[] args) {
            new ProcessTest();
    }   

    At this point, I'm not getting the same results as you. I'm executing cmd.exe w/o args, and using the text area to do multiple directory listings in one go -- so far, the input thread has been able to keep up. Try copying & pasting the following below (I made a few changes to it). If it still doesn't work, it might help to know what operating system you're on, jdk version, etc..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class ProcessTest extends JFrame implements ActionListener {
        private BufferedReader in;
        private BufferedWriter out;
        private JTextArea upperTextArea;
        private JTextArea lowerTextArea;
        private ProcInThread pit;
        private class ProcInThread extends Thread {
            private BufferedReader in;
            private char[] cbuf = new char[8192];
            private int numRead;
            ProcInThread(BufferedReader in) {
                this.in = in;
            public void run() {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                do {
                    try {
                        numRead = in.read(cbuf, 0, cbuf.length);
                        if (numRead < 0) System.out.println("\n***END OF STREAM***\n"); // <-DEBUG CODE
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            lowerTextArea.append(new String(cbuf, 0, numRead));
                } while (numRead != -1);
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
        public ProcessTest() {
            initialiseComponents();
            setBounds(200, 200, 600, 400);
            setVisible(true);
        public void initialiseComponents() {
            Container contentP = getContentPane();
            contentP.setLayout(new BorderLayout());
            upperTextArea = new JTextArea("dir\ndir\ndir\ndir\ndir\ndir\ndir\n");
            lowerTextArea = new JTextArea();
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  new JScrollPane(upperTextArea),
                                                  new JScrollPane(lowerTextArea));
            splitPane.setDividerLocation(200);
            JPanel buttonPanel = new JPanel();
            JButton runButton = new JButton("Start Process");
            runButton.addActionListener(this);
            JButton outputButton = new JButton("Write Output");
            outputButton.addActionListener(this);
            JButton flushButton = new JButton("Flush Output");
            flushButton.addActionListener(this);
            JButton closeOutputButton = new JButton("Close Output");
            closeOutputButton.addActionListener(this);
            JButton inputButton = new JButton("Read Input");
            inputButton.addActionListener(this);
            buttonPanel.add(runButton);
            buttonPanel.add(outputButton);
            buttonPanel.add(flushButton);
            buttonPanel.add(closeOutputButton);
            buttonPanel.add(inputButton);
            contentP.add(buttonPanel, BorderLayout.NORTH);
            contentP.add(splitPane, BorderLayout.CENTER);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void startProcess() {
            try {
                Process process = Runtime.getRuntime().exec("cmd.exe");
                in = new BufferedReader(new InputStreamReader(
                                         process.getInputStream()),8192);
                out = new BufferedWriter(new OutputStreamWriter(
                                          process.getOutputStream()),8192);
                pit = new ProcInThread(in);
                pit.start();
                System.out.println("Process Started.");
            catch(IOException e) {
                e.printStackTrace();
        public void writeOutput() {
            try {
                out.write(upperTextArea.getText().toCharArray());
                System.out.println("Output Write Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void flushOutput() {
            try {
                out.flush();
                System.out.println("Output Flush Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void closeOutput() {
            try {
                out.close();
                System.out.println("Output Close Completed.");
            catch (IOException e) {
                e.printStackTrace();
        public void readInput() {
        public void actionPerformed(ActionEvent e) {
            String action = e.getActionCommand();
            if (action.equalsIgnoreCase("start process")) {
                Thread thread1 = new Thread(){
                    public void run(){
                        startProcess();
                thread1.start();
            else if (action.equalsIgnoreCase("write output")) {
                Thread thread2 = new Thread(){
                    public void run(){
                        writeOutput();
                thread2.start();
            else if (action.equalsIgnoreCase("flush output")) {
                Thread thread3 = new Thread(){
                    public void run(){
                        flushOutput();
                thread3.start();
            else if (action.equalsIgnoreCase("close output")) {
                Thread thread4 = new Thread(){
                    public void run(){
                        closeOutput();
                thread4.start();
            else if (action.equalsIgnoreCase("read input")) {
                Thread thread5 = new Thread(){
                    public void run(){
                    readInput();
                thread5.start();
        public static void main(String[] args) {
            new ProcessTest();
    }

  • Questions on Runtime.exec

    Currently i need to backup a file from the current directory to a Archive directory. So to rename the file in the current directory then move it or copy it into the Archive directory.
    My question is can Runtime.exec () run 2 commands
    first will be "cmd /c start rename A*.zip A_01.zip"
    second will be "cmd /c copy A_01.zip newfolder\A_01.zip" ?
    Reason why i dun wan to run 2 .exec() statement is that i dun wan too many popout screens.
    Hope I can get my solution here.
    Thanks

    don't know whether it works on windoze too, but on unix you can execute several commands seperated by an ";". perhaps this works for exec() too (?)
    so far,
    stefan g.

  • How can I run Runtime.exec command in Java To invoke several other javas?

    Dear Friends:
    I met a problem when I want to use a Java program to run other java processes by Runtime.exec command,
    How can I run Runtime.exec command in Java To invoke several other java processes??
    see code below,
    I want to use HelloHappyCall to call both HappyHoliday.java and HellowWorld.java,
    [1]. main program,
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloHappyCall
         public static void main(String[] args){
              try
                   Runtime.getRuntime().exec("java  -version");
                   Runtime.getRuntime().exec("cmd /c java  HelloWorld "); // here start will create a new process..
                   System.out.println("Never mind abt the bach file execution...");
              catch(Exception ex)
                   System.out.println("Exception occured: " + ex);
    } [2]. sub 1 program
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloWorld
         public static void main(String[] args){
         System.out.println("Hellow World");
    } [3]. Sub 2 program:
    package abc;
    import java.util.*;
    import java.io.*;
    class HappyHoliday
         public static void main(String[] args){
         System.out.println("Happy Holiday!!");
    } When I run, I got following:
    Never mind abt the bach file execution...
    I cannot see both Java version and Hellow World print, what is wrong??
    I use eclipse3.2
    Thanks a lot..

    sunnymanman wrote:
    Thanks,
    But How can I see both programs printout
    "Happy Holiday"
    and
    "Hello World"
    ??First of all, you're not even calling the Happy Holiday one. If you want it to do something, you have to invoke it.
    And by the way, in your comments, you mention that in one case, a new process is created. Actually, new processes are created each time you call Runtime.exec.
    Anyway, if you want the output from the processes, you read it using getInputStream from the Process class. In fact, you really should read that stream anyway (read that URL I sent you to find out why).
    If you want to print that output to the screen, then do so as you'd print anything to the screen.
    in notepad HelloWorld.java, I can see it is opened,
    but in Java, not.I have no idea what you're saying here. It's not relevant whether a source code file is opened in Notepad, when running a program.

  • 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

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Running java process in a while loop using Runtime.exec() hangs on solaris

    I'm writting a multithreaded application in which I'll be starting multiple instances of "AppStartThread" class (given below). If I start only one instance of "AppStartThread", it is working fine. But if I start more than one instance of "AppStartThread", one of the threads hangs after some time (occasionaly). But other threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside another thread?. Here I'm executing the process in a while loop.
    2. Other thing i noticed is the Thread is hanging after completing the process ("java ExecuteProcess"). But the P.waitFor() is not coming out.
    3. Is it bcoz of the same problem as given in Bug ID : 4098442 ?.
    4. Also java 1.2.2 documentation says:
    "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'm running this on sun Solaris/java 1.2.2 standard edition. If any of you have experienced the same problem please help me out.
    Will the same problem can happen on java 1.2.2 enterprise edition.?
    class AppStartThread implements Runnable
    public void run()
    while(true)
    try
    Process P=Runtime.getRuntime().exec("java ExecuteProcess");
    P.waitFor();
    System.out.println("after executing application.");
    P.destroy();
    P = null;
    System.gc();
    catch(java.io.IOException io)
    System.out.println("Could not execute application - IOException " + io);
    catch(java.lang.InterruptedException ip)
    System.out.println("Could not execute application - InterruptedException" + ip);
    catch (Exception e)
    System.out.println("Could not execute application -" + e.getMessage());

    I'm writting a multithreaded application in which I'll
    be starting multiple instances of "AppStartThread"
    class (given below). If I start only one instance of
    "AppStartThread", it is working fine. But if I start
    more than one instance of "AppStartThread", one of the
    threads hangs after some time (occasionaly). But other
    threads are working fine.
    I have the following questions:
    1. Is there any problem with starting a Thread inside
    another thread?. Here I'm executing the process in a
    while loop.Of course this is OK, as your code is always being run by one thread or another. And no, it doesn't depend on which thread is starting threads.
    2. Other thing i noticed is the Thread is hanging
    after completing the process ("java ExecuteProcess").
    But the P.waitFor() is not coming out.This is a vital clue. Is the process started by the Runtime.exec() actually completing or does the ps command still show that it is running?
    3. Is it bcoz of the same problem as given in Bug ID :
    4098442 ?.
    4. Also java 1.2.2 documentation says:
    "Because some native platforms only provide limited
    ed 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. "These two are really the same thing (4098442 is not really a bug due to the reasons explained in the doc). If the program that you are exec'ing produces very much output, it is possible that the buffers to stdout and stderr are filling preventing your program from continuing. On Windows platforms, this buffer size is quite small (hundreds of characters) while (if I recall) on Solaris it is somewhat larger. However, I have seent his behavior causing problem on Solaris 8 in my own systems.
    I once hit this problem when I was 'sure' that I was emitting no output due to an exception being thrown that I wasn't even aware of - the stack trace was more than enough to fill the output buffer and cause the deadlock.
    You have several options. One, you could replace the System.out and System.err with PrintStream's backed up by (ie. on top of) BufferedOutputStream's that have large buffers (multi-K) that in turn are backed up by the original out and err PrintStream's. You would use System.setErr() and System.setOut() very early (static initializer block) in the startup of your class. The problem is that you are still at the mercy of code that may call flush() on these streams. I suppose you could implement your own FilterOutputStream to eat any flush requests...
    Another solution if you just don't care about the output is to replace System.out and System.err with PrintStreams that write to /dev/nul. This is really easy and efficient.
    The other tried and true approach is to start two threads in the main process each time you start a process. These will simply consume anything that is emitted through the stdout and stderr pipes. These would die when the streams close (i.e. when the process exits). Not pretty, but it works. I'd be worried about the overhead of two additional threads per external process except that processes have such huge overhead (considering you are starting a JVM) that it just won't matter. And it's not like the CPU is going to get hit much.
    If you do this frequently in your program you might consider using a worker thread pool (see Doug Lea's Executor class) to avoid creating a lot of fairly short-lived threads. But this is probably over-optimizing.
    Chuck

  • Runtime.exec error - java.lang.NullPointerException

    Hi,
    I am trying out the example code from javaWorld that shows how to use exec to execute external command. The problem is that I aways run into java.lang.NullPointerException on line that has "Process proc = rt.exec(cmd);" I have tried to run the code under Windows XP and Windows 2003; and I get the same error message. Any idea on what might be casing this?
    Thanks,
    // GoodWindowsExec.java
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    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;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    public class GoodWindowsExec
    public static void main(String args[])
    if (args.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    String[] cmd = new String[3];
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    else if( osName.equals( "Windows 95" ) )
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = args[0];
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    }

    What is System.getProperty("os.name") returning when you run on Windows XP or 2003?
    You are only filling in your cmd array when os.name is either Windows NT or Windows 95. In other cases, the elements of cmd are left as null.
    The documentation for Runtime.exec() says you will get a NullPointerException when elements of the array are null:
    http://apidoc.org/view/10563?a=exec%28java.lang.String%5B%5D%29

  • Urgent Help Required : Java Runtime.exec

    Hello,
    We are using the java Runtime.exec in the AIX 4.3.3 environment. Java version 1.1.8. We are consuming the output of the Runtime.exec without using the threads. i.e we are doing a readline on the output stream of the runtime and printing it to th standard output in a loop. When this is over we take the error stream and do the same.
    We have two problems.
    1. A ksh that is run using the java Runtime.exec is showing up multiple processes with the same as a tree structurre when we do a ps.
    Why is this ?
    2. Also whatever we consume from the standard output/error of runtime and print it to system.out is not being output/error. Any pointers on this ?
    Thanks in advance,
    Raj.

    thanks !
    1. we have single thread executing the command. And there are no multiple processes spawned inside the shell script also.
    2. I am sorry about the phrasing. Eventhough we are catching the output stream and error stream and dumping the output correspondingly, the process ( the shell script ) hangs ! And this behaviour is sporadic. Please let us know why the process should hang !
    Thanks,
    rajesh.

  • 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

Maybe you are looking for