External programs can be invoked from Java code using the The exec()
method of the java.lang.Runtime
class . The execand the related ProcessBuilder.start()
method can invoke external programs. Incorrect handling of such external programs can cause unexpected exceptions, denial of service, and other security problems.
returns an object of a subclass of the abstract
class java.lang.Process
. The exitValue()
method can be used to observe the return value of the process. This recommendation discusses several issues resulting from the improper use of the exec()
method. Similarly the ProcessBuilder.start()
method is also prone to misuse.
Noncompliant Code Example
This noncompliant code example invokes notemaker
, a hypothetical cross-platform notepad application, using the exec()
method, which returns an object of a subclass of the abstract
class java.lang.Process
. The program does not exitValue()
method returns the exit value for processes that have terminated; it throws an IllegalThreadStateException
when invoked on an active process. Because this noncompliant example program fails to wait for the notemaker
process to terminate, and throws an IllegalThreadStateException
if the notemaker
process has not completed when the the call to exitValue()
method is called is likely to throw an {IllegalThreadStateException}}.
Code Block | ||
---|---|---|
| ||
public class Exec { public static void main(String args[]) throws IOException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); int exitVal = proc.exitValue(); } } |
...
In this noncompliant code example, the waitFor()
method blocks the calling thread until the invoked process terminates. However, this also has a shortcoming in that, the program may remain blocked for a long time because of the limited buffer size available for the standard output streams on many platforms. The output from the external program may exhaust the buffer, causing this conditionThis prevents the {IllegalThreadStateException}} seen in the previous example. However, the example program may experience an arbitrary delay before termination for any of the following reasons. First, the invoked notemaker process could legitimately require lengthy execution before completion. Although this possibility can present difficulties in practice, it is irrelevant for the purposes of this guideline. Secondly, output from the notemaker process can exhaust the available buffer for the standard output or standard error stream. When this occurs, it can block the notemaker process as well, preventing all forward progress for both processes. Note that many platforms limit the buffer size available for the standard output streams.
Code Block | ||
---|---|---|
| ||
public class Exec { public static void main(String args[]) throws IOException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); int exitVal = proc.waitFor(); } } |
...