1. Waiting for a process to finish: waitFor()
When you launch an external process from Java, it runs independently: does some work, writes to the console, and sometimes hangs (hello, ping with a million packets). But sometimes we need to know when that process has finished, how it finished (success or failure), and—if something goes wrong—be able to “kill” it. In general, just like real life: if you assign a task to someone, it’s good to know whether they completed it, and to have a way to stop them if they suddenly start brewing coffee forever.
When you launch a process via ProcessBuilder, you get a Process object. This object is like a remote control: through it, you can wait for the process to finish, get the exit code, terminate the process, and manage its input/output streams.
How to wait for a process to finish?
Use the waitFor() method:
ProcessBuilder builder = new ProcessBuilder("ping", "google.com", "-c", "3");
Process process = builder.start();
System.out.println("Waiting for the process to finish...");
int exitCode = process.waitFor(); // Blocks the current thread until the process finishes
System.out.println("The process exited with code: " + exitCode);
What happens?
- The program launches an external process (ping).
- After that, the thread where waitFor() is called “sleeps” until the external process finishes.
- As soon as the external process completes, waitFor() returns the exit code (typically 0 = success, non-0 = error).
How to get the exit code?
The waitFor() method returns it. You can also get it separately via exitValue():
int code = process.exitValue();
But be careful: if the process hasn’t finished yet, calling exitValue() throws IllegalThreadStateException. So, you usually wait for completion via waitFor() first, then read the code.
2. Interrupting a process: destroy() and destroyForcibly()
Sometimes an external process runs too long or hangs. For example, someone started ping with 1000 packets, and you have a deadline in 5 seconds. You need a “red button.”
Graceful termination: destroy()
The destroy() method sends a termination signal (SIGTERM on Unix, CTRL-BREAK on Windows), and the process gets a chance to exit cleanly.
Process process = new ProcessBuilder("ping", "google.com").start();
Thread.sleep(2000); // Let it run for 2 seconds
process.destroy(); // Ask it to terminate
Forceful termination: destroyForcibly()
If the process doesn’t respond to polite requests, you can use destroyForcibly(). It’s like pulling the plug.
process.destroyForcibly();
Important: After calling destroy() or destroyForcibly(), you should wait for the process to finish via waitFor(). Sometimes a process needs a moment to “realize” it’s been killed.
3. Waiting for a process with a timeout
Since Java 8+, there’s a method with a timeout:
boolean finished = process.waitFor(5, java.util.concurrent.TimeUnit.SECONDS);
if (finished) {
System.out.println("The process finished on time!");
} else {
System.out.println("The process didn't finish; terminating...");
process.destroy();
}
- If the process finishes within 5 seconds, the method returns true.
- If not, it returns false, and you can take action (for example, terminate the process).
Example: Let’s start a long-running command and try to “kill” it:
ProcessBuilder builder = new ProcessBuilder("ping", "google.com", "-c", "10");
Process process = builder.start();
boolean finished = process.waitFor(2, java.util.concurrent.TimeUnit.SECONDS);
if (!finished) {
System.out.println("The process is taking too long; terminating...");
process.destroy();
// Optionally wait for full termination
process.waitFor();
}
System.out.println("Exit code: " + process.exitValue());
4. Practice: a mini-utility to run a command with a timeout
Let’s write a simple program that launches an external command with a timeout, waits for it to finish, and, if the time is exceeded, terminates the process.
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class ProcessTimeoutDemo {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a command to run (for example, ping google.com):");
String commandLine = scanner.nextLine();
String[] command = commandLine.split(" ");
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
System.out.println("How many seconds to wait for completion?");
int timeout = scanner.nextInt();
boolean finished = process.waitFor(timeout, TimeUnit.SECONDS);
if (finished) {
System.out.println("The process finished on its own. Exit code: " + process.exitValue());
} else {
System.out.println("Time's up! Terminating the process...");
process.destroy();
process.waitFor();
System.out.println("The process was terminated forcibly. Exit code: " + process.exitValue());
}
}
}
Explanation:
- The user enters the command to run.
- The program waits for the specified time.
- If the process hasn’t finished, it is terminated.
Pro tip: On Windows, ping pings 4 times by default, while on Linux it runs indefinitely. For Linux/Mac, add the -c 5 option (for example, ping google.com -c 5).
5. Getting the exit code: what is it and why?
In the command-line world, it’s customary that if a command finishes successfully, it returns 0. If something goes wrong, it returns any other code.
- On Unix-like systems: 0 = success, 1 and above = error.
- On Windows — roughly the same.
You can use this code to make decisions in your Java program:
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("Success!");
} else {
System.out.println("Error! Code: " + exitCode);
}
6. Terminating hung processes
Sometimes a process may just hang—for example, it’s waiting for input from you or can’t connect to the network. If left unattended, it will linger in the system and quietly consume resources.
To prevent this, set a patience limit for the process. The waitFor(timeout, unit) method lets you wait only a certain amount of time for it to finish. If the process doesn’t make it in time—terminate it without hesitation.
After calling destroy(), don’t just wave it off; make sure the process has really exited. Call waitFor() again. And if that doesn’t help—there’s a last resort, destroyForcibly(). It cuts everything off without further discussion.
Example with double termination
boolean finished = process.waitFor(5, TimeUnit.SECONDS);
if (!finished) {
process.destroy();
if (!process.waitFor(2, TimeUnit.SECONDS)) {
process.destroyForcibly();
}
}
Working with Process: important things to remember
When a process finishes, don’t rush to forget about it. Check its output—both standard output and the one where errors are stored. There might be something important: an error message, a warning, or simply a confirmation that everything went well.
After that, be sure to close all related streams—InputStream, OutputStream, and ErrorStream. It’s like turning off the lights when you leave: it saves resources and keeps the system tidy.
And remember: if you terminate a process forcibly, it might not have time to write its output properly. That’s fine—this is normal behavior for such situations.
7. Example: launching a long-running command and terminating it
Suppose we want to launch a long-running process (for example, ping with a large number of packets) and stop it after 3 seconds.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
public class KillLongProcessDemo {
public static void main(String[] args) throws IOException, InterruptedException {
String[] command = {"ping", "google.com"};
// For Linux/Mac: {"ping", "google.com", "-c", "100"}
ProcessBuilder builder = new ProcessBuilder(command);
Process process = builder.start();
// Read the process output in a separate thread
Thread readerThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Ignore
}
});
readerThread.start();
// Wait 3 seconds
if (!process.waitFor(3, TimeUnit.SECONDS)) {
System.out.println("The process is taking too long; terminating...");
process.destroy();
process.waitFor();
}
readerThread.join(); // Wait for the output reader to finish
System.out.println("The process has finished. Exit code: " + process.exitValue());
}
}
8. Common mistakes when managing processes
Error No. 1: Not waiting for the process to finish. If you launch a process and just forget about it (don’t call waitFor()), the process may linger in the system even after your Java program exits. Input/output streams may remain open, leading to memory and file descriptor leaks.
Error No. 2: Improper process termination. You call destroy() but don’t wait for the process to finish via waitFor(). As a result, the process may turn into a “zombie” (especially on Unix-like systems).
Error No. 3: Querying the exit code before the process has finished. Calling exitValue() before the process ends leads to IllegalThreadStateException.
Error No. 4: Not handling exceptions. Methods for working with processes can throw IOException and InterruptedException. Don’t forget to catch them or declare them in the method signature.
Error No. 5: Not reading the process output. If you don’t read stdout and stderr, the process may hang because the output buffer is full.
GO TO FULL VERSION