Java Snippets

Hamburger icon

ProcessBuilder and Runtime

The Process class can be used alone to invoke child processes, as in RunProcess.java:

import java.io.IOException;
import java.util.Arrays;

public class RunProcess {
	
	public static void main(String[] args) throws IOException {
	
		if (args.length <= 0) {
			System.err.println("\nI need a command to run!\n");
			System.exit(-1);
		}

		ProcessBuilder pb   = new ProcessBuilder(args);

		try {
			Process process = pb.start();
			int procretrn   = process.waitFor();
			System.out.println("\nRunning " + Arrays.toString(args) + " returns " + procretrn + "\n");

		} catch (IOException ex){
			System.err.println("\nE/S exception!\n");
			System.exit(-1);

		} catch (InterruptedException ex){
			System.err.println("\nThe child process crashed.\n");
			System.exit(-1);
		}
	}
}

or together with the Runtime class to create native processes, as shown in RuntimeProcess.java:

import java.io.IOException;

public class RuntimeProcess {

	public static void main(String[] args) throws IOException {

		if (args.length <= 0) {
			System.err.println("\nI need a command to run!\n");
			System.exit(-1);
		}

		Runtime runtime = Runtime.getRuntime();

		try {
			Process process = runtime.exec(args);
			System.out.println("Press Enter to continue.");
			System.in.read();
			process.destroy();

		}catch(IOException ex){
			System.err.println("\nE/S exception!\n");
			System.exit(-1);
		}
	}
}

These classes don't use Commons, so you can just compile them like this:

$ javac RunProcess.java
$ javac RuntimeProcess.java

and run them like this:

$ java RunProcess gnome-calculator
$ java RuntimeProcess gnome-calculator

which will open Ubuntu's calculator.

If you open a new terminal and list the active system processes, you will see both the parent and the child:

$ $ ps aux | grep calc
admin     8817  0.2  0.2 3608428 19140 pts/12  Sl+  18:54   0:00 java RuntimeProcess gnome-calculator
admin     8835  0.5  0.2 638936 20320 pts/12   Sl+  18:54   0:00 gnome-calculator
admin     8981  0.0  0.0  18256   924 pts/24   S+   18:54   0:00 grep --color=auto calc

Most used Process methods

Process methods
Method Returns Description
getOutputStream() OutputStream Obtains the output stream of the child conected to the stdin of the parent.
getInputStream() InputStream Obtains the input stream of the child conected to the stdout of the parent.
getErrorStream() InputStream Obtains the error stream of the child conected to the stderr of the parent.
destroy() void Kills the child process.
waitFor() int Parent process waits until the child is finished.
exitValue() int Gets the return value of the child process.
View PB and Runtime's repo