...
This compliant solution spawns two threads to consume the input stream and error stream. Consequently, the process does not blockcannot block indefinitely on those streams.
When the output and error streams are handled separately, they must be emptied independently. Failure to do so can cause the program to block indefinitely.
Code Block | ||
---|---|---|
| ||
class StreamGobbler extends Thread { InputStream is; PrintStream os; StreamGobbler(InputStream is, PrintStream os) { this.is = is; this.os = os; } public void run() { try { int c; while ((c = is.read()) != -1) os.print((char) c); } catch (IOException x) { // handle error } } } public class Exec { public static void main(String[] args) throws IOException, InterruptedException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); // Any error message? StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), System.err); // Any output? StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), System.out); errorGobbler.start(); outputGobbler.start(); // Any error? int exitVal = proc.waitFor(); errorGobbler.join(); // Handle condition where the outputGobbler.join(); // process ends before the threads finish } } |
Exceptions
FIO10-EX0: A Failure to supply input to a process that does not read never reads input from its input stream need not have data supplied there. Similarly, a process that does not send is harmless, and can be beneficial. Failure to empty the output or error streams of a process that never sends output to its output or error streams does not need to empty these is similarly harmless, or even beneficial. Consequently, programs are permitted to ignore the input, output, or error streams when, and only when, the process is guaranteed those streams.
Risk Assessment
Misuse of the exec()
method can result in runtime exceptions and in denial of service vulnerabilities.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ed4c2ab082e5ba07-f83d504e-4c19418c-973aa057-912ab75f4926a2cb0a93a5a5"><ac:plain-text-body><![CDATA[ | [[API 06 | AA. Bibliography#API 06]] | method [exec() | http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String)] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4014cc6761754241-61dc37aa-40094996-92a8b138-c30d516938f66d467e949199"><ac:plain-text-body><![CDATA[ | [[Daconta 00 | AA. Bibliography#Daconta 00]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4fd7b518ac36db0a-79d5a7fa-41994dde-a46bb532-e168026bd78ac0ae5f493181"><ac:plain-text-body><![CDATA[ | [[Daconta 03 | AA. Bibliography#Daconta 03]] | Pitfall 1 | ]]></ac:plain-text-body></ac:structured-macro> |
...