Basically if I start a Notepad by going to start->accessories->notepad then my Java program should close this. Is it possible? If not in Java, any other language?
Asked
Active
Viewed 1,790 times
2 Answers
6
If you know PID of a process use below code to kill a application from Java:
Runtime.getRuntime().exec("taskkill /F /PID <process_id>");
where, is your process id, /F is used to force kill. Note this works only if you're using windows.
From here you can expand this to work for getting process id dynamically and killing instead of hard-coding.
Using system property os.name
you can get name of os and change command accordingly.

Pradeep Simha
- 17,683
- 18
- 56
- 107
-
1`kill -9
` would work for some *nix flavours too. – Chris Jan 15 '13 at 15:14
2
In addition to the post above, you can filter out the PID with this code(don´t know if it can work more simple)
This code does list all Processes, and you can filter out some specific one, if you want
package runtime;
import java.util.Scanner;
public class Process_Check {
public static void main(String[] args) throws Exception {
Processes.ALL_PROCESSES.listProcesses();
}
public static enum Processes implements IProcessListingStrategy {
ALL_PROCESSES;
private IProcessListingStrategy processListing = selectProcessListingStrategy();
public void listProcesses() throws Exception {
processListing.listProcesses();
}
private IProcessListingStrategy selectProcessListingStrategy() {
//todo add support for mac ...
return isWindows() ? new WinProcessListingStrategy() : new LinuxProcessListingStrategy();
}
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0;
}
}
static interface IProcessListingStrategy {
void listProcesses() throws Exception;
}
static abstract class AbstractNativeProcessListingStrategy implements IProcessListingStrategy {
public void listProcesses() throws Exception {
Process process = makeProcessListingProcessBuilder().start();
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
process.waitFor();
}
protected abstract ProcessBuilder makeProcessListingProcessBuilder();
}
static class WinProcessListingStrategy extends AbstractNativeProcessListingStrategy {
@Override
protected ProcessBuilder makeProcessListingProcessBuilder() {
return new ProcessBuilder("cmd", "/c", "tasklist");
}
}
static class LinuxProcessListingStrategy extends AbstractNativeProcessListingStrategy {
@Override
protected ProcessBuilder makeProcessListingProcessBuilder() {
return new ProcessBuilder("ps", "-e");
}
}
}

SomeJavaGuy
- 7,307
- 2
- 21
- 33