I'm wondering how I find the Process ID of another program. (non-java)
When I started programming my program I thought that the process of a .exe stayed the same, but when my program failed I rechecked and realized it changed!
I have tried many different ways from across the internet but none of them had a non-java program as the target.
Here is my current code:
try {
System.out.println("DefaultButton Pressed");
Runtime.getRuntime().exec("taskkill /F /PID "+processID);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Failed to kill the process");
e.printStackTrace();
}
This code trys to kill the process when I press a button
I had code that tried to grab the PID but it failed as well
I have tried this to grab the PID, but it grabs my process's ID (duh). I have been attempting to change the code to be a different non java program but the code still doesn't work.
String processID= ManagementFactory.getRuntimeMXBean().getName();
System.out.println("Process ID for this app = " + processID);
again this is code to grab their own code.
I can not adjust it to work.
Can I even get a PID of another non java process?
EDIT 1 Here is my new code
Process processIdRaw;
try{
processIdRaw = Runtime.getRuntime().exec("tasklist /m | find \"<processname>" ");
System.out.println("Aquired PID");
}
catch(IOException e){
e.printStackTrace();
}
int processID = Integer.parseInt(processIdRaw);
System.out.println("PID:"+processID);
This code is before my other code. The other code comes after this above code.
I think the type Process
doesn't work with int processID = Integer.parseInt(processIdRaw);
I have added the .parseInt
because I though it would find the number from the output.
Errors out before because of the type Process
I could not find a way to make the PID work but!
Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")
works!
try {
System.out.println("DefaultButton Pressed");
Runtime.getRuntime().exec("taskkill /F /IM <processname>");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Failed to kill the process");
e.printStackTrace();
}
To find the process name
1: Run the program you want to kill
2: Run CMD
3: Run the command tasklist
4: Grab the process name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.