tags:

views:

524

answers:

4

I'm looking for some simple tasks like listing all the running process of a user, or kill a particular process by pid etc. Basic unix process management from Java. Is there a library out there that is relatively mature and documented? I could run a external command from the JVM and then parse the standard output/error but that seems like a lot of work and not robust at all. Any suggestions?

A: 

You could try JNA Posix. If the appropriate functions aren't exported by that library, it's very easy to add support for them with JNA (I've done so for many Win32 APIs).

Nat
A: 

The Gnome System Monitor (linux version of Windows Task Manager) uses libgtop2 package. Documnetation here: http://library.gnome.org/devel/libgtop/stable/

Also you can check the source of System Monitor to see how it uses the libgtop2 functions.

CsTamas
Good luck with your JVM stability if you use JNI to call libgtop2 functions from Java :-)
Stephen C
+1  A: 

If you want a pure Java solution, you will need to roll your own I think. Killing a process created by the JVM can be done using Process.destroy(). Listing processes can be done by reading the "/proc" file system. For other stuff you might need to resort to running a native command using Process. It depends on whether your management functionality requires use of syscalls that are not available to a "pure" Java program.

If you go down the JNI + native library route, beware that native pointer problems and native threading issues can kill your JVM. You may also need to deal with building and distributing the native library for multiple architectures, etc.

EDIT: I should add that both kinds of solution will have portability issues. Adjustments will be needed for different flavors of UNIX / Linux.

EDIT 2: I have subsequently learned that the Process.destroy() method cannot send a UNIX SIGKILL interrupt, so that's another limitation on what is possible in pure Java.

Stephen C
A: 

Most of the information you require is available via the /proc filesystem, although you may require the correct permissionings to read everything there. Note that the contents of /proc are Unix-specific - e.g. different on Linux/Solaris, and I have no idea re. MacOSX.

If you want to kill a process you've spawned yourself, then Process.destroy() is worth looking at. Otherwise you're going to have to execute kill. To use this nicely you should send a SIGINT, and if that doesn't work, then send a SIGKILL (to forceably terminate - I'm not sure if Process.destroy() does this)

Brian Agnew