Saturday, May 8, 2010

Windows process/service killing, Get process Id using Java

Recently I came across the situation where I need to automate the finding process id, and kill some windows services based on the value provided in the dashboard. You can read the values at certain interval and complete the actions like killing services, or monitor the process ids, or get list of processes start with same prefix.., hope below helps..


Killing the Service using Java; example code is below –

log.info("Forcefully Killing Services - Taskkill command length: "+arg.length);

String cmd = "cmd.exe /c taskkill /s "+ +" /fi \"services eq "+ +"\" /f >d:\\temp\\log\\output.txt";

//e.g. taskkill /f /im notepad.exe or taskkill /PID 827

log.info("Command to Execute: "+cmd);

//execute the command
Process process = Runtime.getRuntime().exec(cmd);

If you want to get the process id of the service -
log.info("Getting PID - Tasklist command length: "+arg.length);

String cmd = "cmd.exe /c tasklist /s "+ +" /svc /fi \"services eq "+ +"\">d:\\tdp\\log\\output.txt";

//here service name can be prefix, like note*, it will list all the services which starts with note prefix.

log.info("Command to Execute: "+cmd);

Process process = Runtime.getRuntime().exec(cmd);

//to do a synchronous action till you get the result
int exitVal = process.waitFor();

//to check success or failure
log.info("Process exitValue: " + exitVal);

- You can take different actions on the services, and there are other task commands which can be automated using the above steps. However, its not much advisable to use Runtime.getRuntime().exec(). As in case of success or failure you will not always get correct results, sometimes it just stay in the hanging stage. And to read the output, it requires to read the process.getErrorStream(); or you can just move the output to some txt as I am doing in above example...

No comments:

Post a Comment