tags:

views:

159

answers:

3

How can I be notified when a process I did not start ends and is their a way to recover its exit code and or output? the process doing the watching will be running as root/administrator.

+1  A: 

No (not on Unix/Windows, at least). You would have to be the parent process and spawn it off in order to collect the return code and output.

Brian Agnew
A: 

You can kind of do that. On Unix, you can write a script to continuously grep the list of running processes and notify you when the process you're searching for is no longer found.

This is pseudocode, but you can do something like this:

while ( true ) {
    str = ps -Alh | grep "process_name"
    if ( str == '' ) {
        break
    }
    wait(5 seconds)
}
raise_alert("Alert!")

Check the man page for ps. You options may be different. Those are the ones I use on Mac OSX10.4.

AaronM
will this catch the process doing the grepping as well as the process being grepped for?
Arthur Ulfeldt
+2  A: 

You can check whether a process is currently running from java by calling a shell command that lists all the current processes and parsing the output. Under linux/unix/mac os the command is ps, under windows it is tasklist.

For the ps version you would need to do something like:

ProcessBuilder pb = new ProcessBuilder("ps", "-A");
Process p = pb.start();

BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
// Skip first (header) line: "  PID TTY          TIME CMD"
in.readLine();

// Extract process IDs from lines of output
// e.g. "  146 ?        00:03:45 pdflush"
List<String> runningProcessIds = new ArrayList<String>();
for (String line = in.readLine(); line != null; line = in.readLine()) {
    runningProcessIds.add(line.trim().split("\\s+")[0]);
}

I don't know of any way that you could capture the exit code or output.

sea36
After looking into the trace system call and considering 'reparenting' the process I have decided that polling is a whole lot more sane.
Arthur Ulfeldt