基本上,如果我通过开始 - > accessories-> notepad启动记事本,那么我的Java程序应该关闭它。 可能吗? 如果不是Java,任何其他语言?
答案 0 :(得分:6)
如果您知道某个进程的PID使用以下代码来从Java中终止应用程序:
Runtime.getRuntime().exec("taskkill /F /PID <process_id>");
其中,是您的进程ID,/ F用于强制终止。请注意,只有在使用Windows时才有效。
从这里你可以扩展它,以便动态获取进程ID并杀死而不是硬编码。
使用系统属性os.name
,您可以获取操作系统的名称并相应地更改命令。
答案 1 :(得分:2)
除了上面的帖子,您还可以使用此代码过滤掉PID(不知道它是否可以更简单地工作)
此代码会列出所有进程,如果需要,您可以过滤掉一些特定的进程
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");
}
}
}