Thursday, April 8, 2010

Use JSP to get list of running processes or tasklist

I have spent more than 3 hours on this and know there will be more out there experiencing the same problem. There are various pages on the net outlining how to get the tasklist on Windows in Java using the Runtime and Process classes and executing "cmd /c tasklist".

The above mentioned code runs perfectly when executed as a Java app via a main method but when executed through JSP or servlet, it fails to execute.

Here is the problem. When you run a commandline program using JSP, the PATH environment
variable is not the same as when you execute a regular Java app or batch
file. So when you call "cmd /c tasklist" using Runtime.getRuntime().exec it executes with the PATH variable as empty, which means that dll files needed by tasklist are not found.

Long story short, want to get a list of running processes in JSP, use the following code:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("cmd /c set PATH=C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem& tasklist");
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

String line;
while ((line = bufferedreader.readLine()) != null) {
out.print( line.toLowerCase() + "
" );
}

bufferedreader.close();

You will have to modify the PATH to match your own environment.

If you are having problems executing other commandline programs using JSP or Servlets, chances are that you are experiencing the same problem.

No comments: