Java에서 현재 열려 있는 창/프로세스 목록을 가져오려면 어떻게 해야 합니까?
Java를 사용하여 로컬 머신의 현재 열린 창이나 프로세스를 얻는 방법을 아는 사람이 있습니까?
제가 하려고 하는 것은 현재 열려 있는 태스크, 윈도 또는 프로세스를 나열하는 것입니다.Windows 태스크 매니저에서처럼 열려 있지만 가능하면 Java만 사용하는 멀티플랫폼 접근 방식을 사용합니다.
이것은 명령어 "ps - e"에서 프로세스 목록을 해석하는 또 다른 방법입니다.
try {
String line;
Process p = Runtime.getRuntime().exec("ps -e");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
Windows 를 사용하고 있는 경우는, 다음의 행을 변경할 필요가 있습니다.「 Process p = Runtime . getRun ." 등...(세 번째 줄), 다음과 같은 경우:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
정보가 도움이 되길 바랍니다!
마지막으로 Java 9+에서는 다음을 사용할 수 있습니다.
public static void main(String[] args) {
ProcessHandle.allProcesses()
.forEach(process -> System.out.println(processDetails(process)));
}
private static String processDetails(ProcessHandle process) {
return String.format("%8d %8s %10s %26s %-40s",
process.pid(),
text(process.parent().map(ProcessHandle::pid)),
text(process.info().user()),
text(process.info().startInstant()),
text(process.info().commandLine()));
}
private static String text(Optional<?> optional) {
return optional.map(Object::toString).orElse("-");
}
출력:
1 - root 2017-11-19T18:01:13.100Z /sbin/init
...
639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
...
23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo
Windows 에서는, JNA 를 사용하는 대체 방법이 있습니다.
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.win32.W32APIOptions;
public class ProcessList {
public static void main(String[] args) {
WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);
WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
while (winNT.Process32Next(snapshot, processEntry)) {
System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
}
winNT.CloseHandle(snapshot);
}
}
제가 생각할 수 있는 유일한 방법은 사용자를 위해 작업을 수행하는 명령줄 애플리케이션을 실행하고 출력을 스크랩하는 것입니다(Linux의 ps나 Window의 태스크리스트 등).
유감스럽게도 이는 양쪽에서 데이터를 읽으려면 몇 가지 구문 분석 루틴을 작성해야 한다는 것을 의미합니다.
Process proc = Runtime.getRuntime().exec ("tasklist.exe");
InputStream procOutput = proc.getInputStream ();
if (0 == proc.waitFor ()) {
// TODO scan the procOutput for your data
}
YAJSW(Yet Another Java Service Wrapper)는 JNA 기반의 org.rzo를 구현한 것으로 보인다.yajsw.os.win32, Linux, bsd 및 Solaris용 TaskList 인터페이스로 LGPL 라이선스가 있습니다.이 코드를 직접 호출해 본 적은 없지만, YAJSW는 과거에 사용해 본 적이 있기 때문에 크게 걱정하지 않아도 됩니다.
jProcesses를 사용하여 실행 중인 프로세스 목록을 쉽게 검색할 수 있습니다.
List<ProcessInfo> processesList = JProcesses.getProcessList();
for (final ProcessInfo processInfo : processesList) {
System.out.println("Process PID: " + processInfo.getPid());
System.out.println("Process Name: " + processInfo.getName());
System.out.println("Process Used Time: " + processInfo.getTime());
System.out.println("Full command: " + processInfo.getCommand());
System.out.println("------------------");
}
플랫폼 중립적인 방법은 없습니다.Java 1.6 릴리스에서는 를 사용하여 URI를 참조, 편집, 메일링, 열기 및 인쇄할 수 있는 "데스크탑" 클래스가 추가되었습니다.언젠가 이 클래스가 지원 과정으로 확대될 수도 있지만, 저는 그렇게 생각하지 않습니다.
Java 프로세스에만 관심이 있는 경우 java.lang.management api를 사용하여 JVM의 스레드/메모리 정보를 얻을 수 있습니다.
Windows 의 경우는, 다음과 같이 사용합니다.
Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start();
new Thread(() -> {
Scanner sc = new Scanner(process.getInputStream());
if (sc.hasNextLine()) sc.nextLine();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] parts = line.split(",");
String unq = parts[0].substring(1).replaceFirst(".$", "");
String pid = parts[1].substring(1).replaceFirst(".$", "");
System.out.println(unq + " " + pid);
}
}).start();
process.waitFor();
System.out.println("Done");
이 기능은 JRE가 번들된 앱에 유용할 수 있습니다. 응용 프로그램을 실행 중인 폴더 이름을 검색합니다. 따라서 응용 프로그램이 다음 위치에서 실행되는 경우:
C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe
J9에서 이미 실행 중인지 확인하려면 다음을 수행합니다.
public static void main(String[] args) {
AtomicBoolean isRunning = new AtomicBoolean(false);
ProcessHandle.allProcesses()
.filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp"))
.forEach((process) -> {
isRunning.set(true);
});
if (isRunning.get()) System.out.println("SomeJavaApp is running already");
}
코드를 사용한 해석ps aux
Linux 및tasklist
보다 일반적인 것이 나타날 때까지 윈도우가 최선의 선택입니다.
Windows 의 경우는, http://www.rgagnon.com/javadetails/java-0593.html 를 참조해 주세요.
Linux는 다음 결과를 파이핑할 수 있습니다.ps aux
통해.grep
처리/실행도 빠르고 쉽게 할 수고를 덜 수고를 덜 수 있습니다.창문도 비슷한 걸 찾을 수 있을 거예요.
아래 프로그램은 Java 9+ 버전에만 호환됩니다.
Current Process 정보를 얻으려면
public class CurrentProcess {
public static void main(String[] args) {
ProcessHandle handle = ProcessHandle.current();
System.out.println("Current Running Process Id: "+handle.pid());
ProcessHandle.Info info = handle.info();
System.out.println("ProcessHandle.Info : "+info);
}
}
실행 중인 모든 프로세스에 대해
import java.util.List;
import java.util.stream.Collectors;
public class AllProcesses {
public static void main(String[] args) {
ProcessHandle.allProcesses().forEach(processHandle -> {
System.out.println(processHandle.pid()+" "+processHandle.info());
});
}
}
String line;
Process process = Runtime.getRuntime().exec("ps -e");
process.getOutputStream().close();
BufferedReader input =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
이용해야 합니다.process.getOutputStream.close()
그렇지 않으면 루프 중에 잠깁니다.
package com.vipul;
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class BatchExecuteService extends Applet {
public Choice choice;
public void init()
{
setFont(new Font("Helvetica", Font.BOLD, 36));
choice = new Choice();
}
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
List<String> processList = new ArrayList<String>();
public void run() {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("D:\\server.bat");
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(
inputStream);
BufferedReader bufferedrReader = new BufferedReader(
inputstreamreader);
BufferedReader bufferedrReader1 = new BufferedReader(
inputstreamreader);
String strLine = "";
String x[]=new String[100];
int i=0;
int t=0;
while ((strLine = bufferedrReader.readLine()) != null)
{
// System.out.println(strLine);
String[] a=strLine.split(",");
x[i++]=a[0];
}
// System.out.println("Length : "+i);
for(int j=2;j<i;j++)
{
System.out.println(x[j]);
}
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
}
}
You can create batch file like
태스크리스트/v/FI "STATUS eq 실행 중"/FO "CSV"/FI "Username eq LHPL002\soft"/FI "MEMUSAGE gt 10000"/FI "Windowtitle ne N/A"/NH
이것은 작업을 가져오고 이름을 가져오는 함수의 코드이며, 목록에서 액세스할 수 있는 목록에 추가합니다.데이터를 사용하여 임시 파일을 만들고 파일을 읽고 .exe 접미사를 사용하여 작업 이름을 가져옵니다.또한 프로그램이 System.exit(0)를 사용하여 종료되었을 때 삭제될 파일을 정렬합니다.또한 사용자가 실수로 프로그램을 실행하는 프로세스를 모두 종료하지 않도록 태스크와 java.exe를 가져오는 데 사용되는 프로세스도 숨깁니다.
private static final DefaultListModel tasks = new DefaultListModel();
public static void getTasks()
{
new Thread()
{
@Override
public void run()
{
try
{
File batchFile = File.createTempFile("batchFile", ".bat");
File logFile = File.createTempFile("log", ".txt");
String logFilePath = logFile.getAbsolutePath();
try (PrintWriter fileCreator = new PrintWriter(batchFile))
{
String[] linesToPrint = {"@echo off", "tasklist.exe >>" + logFilePath, "exit"};
for(String string:linesToPrint)
{
fileCreator.println(string);
}
fileCreator.close();
}
int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();
if(task == 0)
{
FileReader fileOpener = new FileReader(logFile);
try (BufferedReader reader = new BufferedReader(fileOpener))
{
String line;
while(true)
{
line = reader.readLine();
if(line != null)
{
if(line.endsWith("K"))
{
if(line.contains(".exe"))
{
int index = line.lastIndexOf(".exe", line.length());
String taskName = line.substring(0, index + 4);
if(! taskName.equals("tasklist.exe") && ! taskName.equals("cmd.exe") && ! taskName.equals("java.exe"))
{
tasks.addElement(taskName);
}
}
}
}
else
{
reader.close();
break;
}
}
}
}
batchFile.deleteOnExit();
logFile.deleteOnExit();
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException | InterruptedException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (NullPointerException ex)
{
// This stops errors from being thrown on an empty line
}
}
}.start();
}
public static void killTask(String taskName)
{
new Thread()
{
@Override
public void run()
{
try
{
Runtime.getRuntime().exec("taskkill.exe /IM " + taskName);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
언급URL : https://stackoverflow.com/questions/54686/how-to-get-a-list-of-current-open-windows-process-with-java
'programing' 카테고리의 다른 글
yii2에서 드롭다운 목록을 만드는 방법 (0) | 2022.10.01 |
---|---|
메서드를 스태틱으로 선언함으로써 얻을 수 있는 이점은 무엇입니까? (0) | 2022.10.01 |
SQL Update 문을 실행하기 전에 테스트하는 방법 (0) | 2022.10.01 |
haproxy를 mariadb 클러스터의 밴랜서로 사용하지만 쿼리 중에 연결이 끊어졌습니다. (0) | 2022.10.01 |
현재 스레드가 메인 스레드가 아닌지 확인하는 방법 (0) | 2022.10.01 |