import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ParentProcess {
public static String SUBPROCESS = SubProcess.class.getName();
public static void main(String[] args) {
try {
System.out
.println("This Java process will spawn a Java sub-process using the exec() method on Runtime.");
System.out
.println("The sub-process' standard ouput and error streams will be redirected to files named");
System.out
.println("'stdout.log' and 'stderr.log' in the current directory.");
System.out
.println("The sub-process will send it's System.out and System.err to");
System.out.println("the file 'subprocess.log'.\n");
String command = buildCommandLine();
System.out.println("Executing '" + command + "'\n");
/*
* see
* http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String)
*/
Process process = Runtime.getRuntime().exec(command);
ProcessLogger errorStream = new ProcessLogger(process
.getErrorStream(), new FileOutputStream("stderr.log"),
"stderr.log");
ProcessLogger outputStream = new ProcessLogger(process
.getInputStream(), new FileOutputStream("stdout.log"),
"stdout.log");
errorStream.start();
outputStream.start();
System.out
.println("Now do a kill -QUIT to the sub-process PID and note the");
System.out.println("thread dump appears in the 'stdout.log'.");
int exitVal = process.waitFor();
System.out.println("exitValue " + exitVal);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static String buildCommandLine() {
StringBuffer cmdBuilder = new StringBuffer(System
.getProperty("java.home"));
cmdBuilder.append(File.separatorChar);
cmdBuilder.append("bin");
cmdBuilder.append(File.separatorChar);
cmdBuilder.append("java -cp ");
cmdBuilder.append(System.getProperty("java.class.path"));
cmdBuilder.append(' ');
cmdBuilder.append(SUBPROCESS);
String command = cmdBuilder.toString();
return command;
}
} |