How to check if pid works on Windows with Java:
Windows task list command:
The DOS tasklist shows some output about which processes are running:
C:\Documents and Settings\eric>tasklist Image Name PID Session Name Session
The second column is the PID
You can use tasklist to get information about a specific PID:
tasklist /FI "PID eq 1300"
prints:
Image Name PID Session Name Session
The answer means that the PID is running.
If you request a PID that does not exist, you will receive the following:
C:\Documents and Settings\eric>tasklist /FI "PID eq 1301" INFO: No tasks running with the specified criteria. C:\Documents and Settings\eric>
Java function could do this automatically automatically
This function will only work on Windows systems with 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."); } } }
The above Java code prints a list of all running processes, then prints:
is PID 1300 running? true
source share