0

So here is my code:

System.out.print("hellow");
    try {
        int x;
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("java CPU/memory");
        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = null;
        while((line = in.readLine())!=null) {
            System.out.println(line);
        }
        proc.waitFor();
    } catch (Throwable t)
    {
        t.printStackTrace();
    }
 $

When I run java CPU/CPU in cmd I get "hellowhello" with exit value of 0

But when I run it in eclipse I just get "hello" with exit value of 1

Any idea?

2 Answers2

2

You have different system environment in executing from command string and executing from Eclipse.

Variables of environment are valuable : PATH, JAVA_HOME or JRE_HOME and your current worikng directory.

I use ProcessBuilder in cases, when I must be sure in environment, that is provided for external process like yours "java CPU/memory".

I think that first of all your external process have wrong working directory. In ProcessBuilder you can point on it with:

ProcessBuilder pb = new ProcessBuilder("java", "CPU/MEMORY");   
pb.directory(new File("/home/myhome/myjavaprojects"));
Process p = pb.start();
Arcady
  • 56
  • 2
0

Don't ignore the ErrorStream. If you read it (in its own thread), you'll see what you're doing wrong.

For example:

import java.io.*;

public class Foo001 {
   public static void main(String[] args) {
      System.out.println("hellow");
      try {
         int x;
         Runtime rt = Runtime.getRuntime();
         Process proc = rt.exec("java CPU/memory");
         final BufferedReader in = new BufferedReader(new InputStreamReader(
               proc.getInputStream()));
         final BufferedReader err = new BufferedReader(new InputStreamReader(
               proc.getErrorStream()));
         new Thread(new ReadLiner(in, "in")).start();
         new Thread(new ReadLiner(err, "err")).start();
         // proc.waitFor(); // not sure that this is needed
      } catch (Throwable t) {
         t.printStackTrace();
      }
   }
}

class ReadLiner implements Runnable {
   private BufferedReader br;
   private String text;

   public ReadLiner(BufferedReader br, String text) {
      this.br = br;
      this.text = text;
   }

   @Override
   public void run() {
      String line = null;
      try {
         while ((line = br.readLine()) != null) {
            System.out.println(text + ": " + line);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373