Как проверить, работает ли pid в Windows с Java:
Команда списка задач Windows:
Команда DOS tasklist
показывает некоторые выходные данные о запущенных процессах:
C:\Documents and Settings\eric>tasklist
Image Name PID Session Name Session# Mem Usage
========================= ====== ================ ======== ============
System Idle Process 0 Console 0 28 K
System 4 Console 0 244 K
smss.exe 856 Console 0 436 K
csrss.exe 908 Console 0 6,556 K
winlogon.exe 932 Console 0 4,092 K
....
cmd.exe 3012 Console 0 2,860 K
tasklist.exe 5888 Console 0 5,008 K
C:\Documents and Settings\eric>
Второй столбец - PID
Вы можете использовать tasklist
, чтобы получить информацию о конкретном PID:
tasklist /FI "PID eq 1300"
печать:
Image Name PID Session Name Session# Mem Usage
========================= ====== ================ ======== ============
mysqld.exe 1300 Console 0 17,456 K
C:\Documents and Settings\eric>
Ответ означает, что PID работает.
Если вы запросите PID, который не существует, вы получите это:
C:\Documents and Settings\eric>tasklist /FI "PID eq 1301"
INFO: No tasks running with the specified criteria.
C:\Documents and Settings\eric>
Java-функция может делать вышеупомянутое автоматически
Эта функция будет работать только в системах Windows с tasklist
.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class IsPidRunningTest {
public static void main(String[] args) {
//this function prints all running processes
showAllProcessesRunningOnWindows();
//this prints whether or not processID 1300 is running
System.out.println("is PID 1300 running? " +
isProcessIdRunningOnWindows(1300));
}
/**
* Queries {@code tasklist} if the process ID {@code pid} is running.
* @param pid the PID to check
* @return {@code true} if the PID is running, {@code false} otherwise
*/
public static boolean isProcessIdRunningOnWindows(int pid){
try {
Runtime runtime = Runtime.getRuntime();
String cmds[] = {"cmd", "/c", "tasklist /FI \"PID eq " + pid + "\""};
Process proc = runtime.exec(cmds);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
//Search the PID matched lines single line for the sequence: " 1300 "
//if you find it, then the PID is still running.
if (line.contains(" " + pid + " ")){
return true;
}
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Cannot query the tasklist for some reason.");
System.exit(0);
}
return false;
}
/**
* Prints the output of {@code tasklist} including PIDs.
*/
public static void showAllProcessesRunningOnWindows(){
try {
Runtime runtime = Runtime.getRuntime();
String cmds[] = {"cmd", "/c", "tasklist"};
Process proc = runtime.exec(cmds);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Cannot query the tasklist for some reason.");
}
}
}
Приведенный выше код Java печатает список всех запущенных процессов, а затем печатает:
is PID 1300 running? true