Java System Calls: Difference between revisions

From Wiki
Jump to navigation Jump to search
 
(No difference)

Latest revision as of 22:07, 31 January 2011

In Unix,

/bin/sh -c <commands>

is a way to ask the shell to process <commands>

In Windows, you may need

command \c dir

or

cmd \c dir

to execute DOS shell commands like dir. Otherwise, the command name should suffice.

StreamGobbler

See http://hacks.oreilly.com/pub/h/1092 for a good description of this

import java.io.*;

public class StreamGobbler extends Thread {
  private InputStream is;
  private StringBuffer buffer;

  StreamGobbler(InputStream is, StringBuffer buffer) {
    this.is = is;
    this.buffer = buffer;
    this.start();
  }
 
  StreamGobbler(InputStream is) {
    this(is, null);
  }

  public void run() {
    int nextChar;
    if (buffer == null) {
      try {
        while ((nextChar = is.read()) != -1) {} // do nothing
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    } else {
      try {
        while ((nextChar = is.read()) != -1) {
          buffer.append((char) nextChar);
        }
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
    }
  }
}

booleanCommand

public static boolean booleanCommand(String command) {
  Runtime rt = Runtime.getRuntime();
  String[] callAndArgs = {"/bin/bash", "-c", command};
  int exitValue = Integer.MIN_VALUE;
  Process child = null;
  try {
    child = rt.exec(callAndArgs);
    StreamGobbler errorGobbler = new StreamGobbler(child.getErrorStream());
    StreamGobbler inputGobbler = new StreamGobbler(child.getInputStream());
    exitValue = child.waitFor();
  } catch (IOException e) {
    logger.error("IOException starting process!", e);
  } catch (InterruptedException e) {
    logger.error("Interrupted waiting for process!", e);
  }
  if (exitValue == Integer.MIN_VALUE) {
    logger.error("boolean command " + command + " failed to execute!");
  }
  return (exitValue == 0);
}

stringCommandIgnoreReturnValue

public static String stringCommandIgnoreReturnValue(String command) {
  Runtime rt = Runtime.getRuntime();
  String[] callAndArgs = {"/bin/bash", "-c", command};
  StringBuffer inputBuffer = new StringBuffer();
  int exitValue = Integer.MIN_VALUE;
  Process child = null;
  try {
    child = rt.exec(callAndArgs);
    StreamGobbler errorGobbler = new StreamGobbler(child.getErrorStream());
    StreamGobbler inputGobbler = new StreamGobbler(child.getInputStream(), inputBuffer);
    exitValue = child.waitFor();
  } catch (IOException e) {
    e.printStackTrace();
    System.err.println("IOException starting process!");
  } catch (InterruptedException e) {
    System.err.println("Interrupted waiting for process!");
  }
  if (exitValue == Integer.MIN_VALUE) {
    throw new IllegalStateException("command " + command + " failed to return any output!");
  }
  return inputBuffer.toString();
}