// start up the command
Process child =
new ProcessBuilder("/bin/ls", opts, dir).
redirectErrorStream(true).start();
// ... as before ...
}
23.2.4. Portability
Any program that uses exec or ProcessBuilder is not portable across all systems. Not all environments
have processes, and those that have them can have widely varying commands and syntax for invoking those
commands. Also, because running arbitrary commands raises serious security issues, the system may not
allow all programs to start processes. Be very cautious about choosing to do this because it has a strong
negative impact on your ability to run your program everywhere.
Exercise 23.2: Write a program that runs exec on its command-line arguments and prints the output from the
command, preceding each line of output by its line number.
Exercise 23.3: Write a program that runs exec on command-line arguments and prints the output from the
command, killing the command when a particular string appears in the output.
23.3. Shutdown
Normally, an execution of a virtual machine terminates when the last user thread terminates. A Runtime can
also be shut down explicitly with its exit method, passing an integer status code that can be communicated
to the environment executing the virtual machinezero to indicate successful completion of a task and non-zero
to indicate failure. This method abruptly terminates all threads in the runtime system no matter what their
state. They are not interrupted or even stopped. They simply cease to exist as the virtual machine itself stops
runningno finally clauses are executed.
In either case, when exit is invoked or the last user thread terminates, the shutdown sequence is initiated.
The virtual machine can also be shut down externally, such as by a user interrupting the virtual machine from
a keyboard (on many systems by typing control-C) or when the user logs out or the computer is shut down.
All the methods related to shutting down the runtime system are security checked and throw
SecurityException if you don't have required permissions.
23.3.1. Shutdown Hooks
An application can register a shutdown hook with the runtime system. Shutdown hooks are threads that
represent actions that should be taken before the virtual machine exits. Hooks typically clean up external
resources such as files and network connections.
public voidaddShutdownHook(Thread hook)
Registers a new virtual-machine shutdown hook. If hook has already been
registered or has already been started an IllegalArgumentException
is thrown.