Illustrates the monitoring of an external process as well as input and output error streams.
Overview
To execute an external process you have to create an instance of the TerminalMonitoredProcess class. The constructor requires the following parameters:
The following example shows the creation of an external process. At the end of this example when call TerminalMonitoredProcess.destroy, one of the methods will be executed onClose with terminal output for the external process.
The example below uses the Terminal Monitored Process:
. . .
TerminalMonitoredProcess process = new TerminalMonitoredProcess(//
new String[] { // command line parameters - execute "ls -l /"
"/bin/ls", "-l", "/" // provides listing of the root folder
},
300, // a small period that monitored process waits to reduce CPU load
true, // run Garbage Collector after process exits
new TerminalMonitoredProcessCallback() {
public void onErrLine(String line, TerminalMonitoredProcess process) {
System.out.println("ERR: " + line);
}
public void onOutLine(String line, TerminalMonitoredProcess process) {
System.out.println("OUT: " + line);
}
public void onClose(MonitoredProcess process) {
System.out.println("Process closed: " + process);
}
public void onCloseHang(MonitoredProcess process) {
System.out.println("Process hanged: " + process);
}
});
// let the process execute for maximum 4 seconds
process.waitFor(4000);
// make sure process is destroyed
int exitValue = process.destroy(1000);
System.out.println("Process closed with exit value " + exitValue);
}
. . .
The console/terminal output when executing external process is shown below:
OUT: drwxr-xr-x 2 root root 4096 2015-03-08 00:58 selinux
OUT: drwxr-xr-x 2 root root 4096 2014-04-02 13:08 srv
OUT: drwxr-xr-x 11 root root 0 2014-07-13 14:43 sys
OUT: drwxrwxrwt 8 root root 4096 2014-10-03 15:22 tmp
OUT: drwxrwxr-x 3 root root 4096 2014-09-21 12:23 tools
OUT: drwxr-xr-x 12 root root 4096 2015-01-17 11:22 usr
OUT: drwxr-xr-x 13 root root 4096 2015-02-12 13:16 var
OUT: lrwxrwxrwx 1 root root 25 2015-03-02 13:08 vmlinuz -> boot/vmlinuz-2.6.26-2-686
Process closed: com.prosyst.util.process.TerminalMonitoredProcess@586a50
Process closed with exit value 0
Bundle with ID 20 was started.
fw>$