Mustafa
Mustafa

Reputation: 981

List of running programs in Linux using java

I'm trying to code a task manager for Linux using Java.

I need to get a list of running programs. And other info like: memory usage, cpu usage ...

Is this possible from Java?

Thanks.

Upvotes: 0

Views: 2061

Answers (3)

David Weiser
David Weiser

Reputation: 5205

Try using the exec(String command). You can then get the input stream from the resulting Process.

Upvotes: 0

das_weezul
das_weezul

Reputation: 6142

try {
    // Execute command
    String command = "ps aux";
    Process child = Runtime.getRuntime().exec(command);

    // Get the input stream and read from it
    InputStream in = child.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
        process((char)c);
    }
    in.close();
} catch (IOException e) {
}

Source (modified): http://www.exampledepot.com/egs/java.lang/ReadFromCommand.html

Upvotes: 6

Edwin Buck
Edwin Buck

Reputation: 70959

It is possible, in systems that use the /proc virtual filesystem, you can just transverse the directories and cat out the information under /proc.

The numbered directories in /proc are the process ids of running processes, and the items within those directories help describe the process.

For memory usage and cpu information, there are /proc/meminfo and /proc/cpuinfo (and a lot more). Hopefully that will get you started.

For systems that lack the /proc virtual filesystem, you need to use JNI to bind to C code which will do kernel API calls, or attempt to run local command line programs thorough an exec while piping and parsing the output back into the Java program.

Upvotes: 1

Related Questions