Rectangle 27 0

How to get a list of current open windowsprocess with Java?


Process p = Runtime.getRuntime().exec
    (System.getenv("windir") +"\\system32\\"+"tasklist.exe");
try {
    String line;
    Process p = Runtime.getRuntime().exec("ps -e");
    BufferedReader input =
            new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((line = input.readLine()) != null) {
        System.out.println(line); //<-- Parse data here.
    }
    input.close();
} catch (Exception err) {
    err.printStackTrace();
}

If you are using Windows, then you should change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this:

It should be noted that the "windows specific" bit at the bottom appears to be unnecessary. On Windows 10, (.exec (Runtime/getRuntime) "tasklist")) (in Clojure, using Java-interop) correctly returns the tasklist process, even without specifying a directory.

On Windows, run tasklist.exe /fo csv /nh to get the list in CSV format, that's much easier to parse.

This is another approach to parse the the process list from the command "ps -e":

Why wouldn't it work if I add a | grep java ? i.e. ps -elf | grep java won't return a thing, but ps -elf would work as expected.

but it is not showing the jar name. My executable jar name is helloDemo.jar. but it is not showing anything for it

how to get the process start time and end time

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


try{
        Process proc = Runtime.getRuntime().exec("wmic.exe");
        BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream());
        oStream.write("process get caption");
        oStream.flush();
        oStream.close();
        String line;
        while ((line = input.readLine()) != null){
            if(!line.isEmpty() && !line.startsWith("wmic:root\\cli")) {
                System.out.println(line);
            }
        }
        input.close();
}catch (IOException ioe){ioe.printStackTrace();}

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


YAJSW (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven't tried calling this code directly, but YAJSW works really well when I've used it in the past, so you shouldn't have too many worries.

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


Process proc = Runtime.getRuntime().exec ("tasklist.exe");
InputStream procOutput = proc.getInputStream ();
if (0 == proc.waitFor ()) {
    // TODO scan the procOutput for your data
}

On Windows, the tasklist program can be configured to output CSV :)

The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist).

Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.

Yep,I already thought about that too, but I tough it could be done with Java only. And I think I would be better to use "ps -aux" instead of top. Thanks for the quick answer!

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


GetModuleFileName
import com.sun.jna.Native;
import com.sun.jna.platform.win32.*;
import com.sun.jna.win32.W32APIOptions;

public class ProcessList {

    public static void main(String[] args) {
        WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);

        WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));

        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();

        while (winNT.Process32Next(snapshot, processEntry)) {
            System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile));
        }

        winNT.CloseHandle(snapshot);
    }
}

@ChristopherDancy not sure if you still need an answer but for completeness and and as it wasn't mentioned here either: Winodws Managment Information Command-line (or simply wmic.exe) provides a way to retrieve plenty of information of running applications - WMIC PROCESS or to restrict the output for a specific process: WMIC PROCESS WHERE name='theName'. You can use further filters to limit the output if needed. The command line is included in the CommandLine column of the table returned (= 2nd column)

The only problem w/ this is that it gives only the path of the process NOT the entire command line. Is there a way to get the full command line of the process (i.e. 'ant.bat -f helloWorld.ext')?

This only gives the command name NOT the entire command line. Is there a way to get the entire command line?

how to check for a particular process like xyz.exe is running or not?

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


List<ProcessInfo> processesList = JProcesses.getProcessList();

for (final ProcessInfo processInfo : processesList) {
    System.out.println("Process PID: " + processInfo.getPid());
    System.out.println("Process Name: " + processInfo.getName());
    System.out.println("Process Used Time: " + processInfo.getTime());
    System.out.println("Full command: " + processInfo.getCommand());
    System.out.println("------------------");
}

I guess you talk about windows implementation. Yes, normally WMI queries take some time. As always it depends on the use case. If you need to perform the query every 10 ms, yes, it is too slow.

It is fine, but what i was looking for: In your process startTime you have limited the given time for one day (hh:mm:ss) if i am not wrong. Is there any option to get also the date + time ( yyyy-mm-dd-hh:mm:ss) ?

Ok, if you want you can create an issue in the github project and I will eventually take a look and see if I can improve performance in Win. In fact I used it on Linux so I did not pay much attention to win implementation :-S

You can easily retrieve the list of running processes using jProcesses

this library seems to be very slow... is there a reason for this (or is it general java + wmi interop across vbs?

yes i was talking about win, in linux i spotted the use of "ps...<options>" so i guess it should be much faster

Note
Rectangle 27 0

How to get a list of current open windowsprocess with Java?


If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.

There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.

Note