VintageBigBlue.org

 
Nov 11, 2108

Using Java to execute a command

First a Warning

Running a command from Java is not like running it from a terminal command prompt. The terminal command prompt comes with an environment including the PATH variable. The Java runtime exec method does not have a PATH in it's shortest form and requires the full path to the program you wish to execute. You can set up an enviroment in the following manner:

hercChild = rt.exec(command, "var1=abc;var2=def", new File("/NetMF/AuxData/PDP8"));

Where the third parameter is the working directory the started program will be given.

This is how I open and control the Hercules process on the java server in my home.

    StdInThread stdInThread ;
    StdErrThread stdErrThread ;
    String[] command = new String[6] ;
    command[0] = "/usr/bin/hercules" ;
    command[1] = "-d" ;
    command[2] = "-l" ;
    command[3] = "dyngui" ;
    command[4] = "-f" ;
    command[5] = "/Share/MVS/conf/tk3upd.conf" ;
    try { hercChild = Runtime.getRuntime().exec(command);
    hcInp = new BufferedReader(new InputStreamReader(hercChild.getInputStream())) ;
    stdInThread = new StdInThread() ;
    stdInThread.start() ;
    hcErr = new BufferedReader(new InputStreamReader(hercChild.getErrorStream())) ;
    stdErrThread = new StdErrThread() ;
    stdErrThread.start() ;
    hcOutp = new PrintWriter(hercChild.getOutputStream()) ;
} catch (Exception e) { 
    e.printStackTrace(System.out) ;
}
// end of start up


class StdInThread extends Thread {
int StdInThread() {
   return(0) ;
}
@Override
public void run() {
String inpLine ;
  while (running == true) {
      try {
      inpLine = hcInp.readLine() ;
      } catch (Exception e) {
        running = false ;
      }
  }
 }
}



class StdErrThread extends Thread {
int StdErrThread() {
   return(0) ;
}
@Override
public void run() {
String inpLine ;
  while (running == true) {
      try {
      inpLine = hcErr.readLine() ;
      } catch (Exception e) {
        running = false ;
      }
  }
 }
}


You cannot just open the streams to the process. If the input and error stream buffers get full the process will hang. You must read from those streams if data is available even if you just discard it. In the above example threads are started to read the stdin and stderr, the results of which are discarded.


Contact Us
This Site's Privacy Policy
Google's privacy policies