Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91617

how to wait for a process to end in java or clojure

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.

Upvotes: 2

Views: 1211

Answers (4)

rogerdpack
rogerdpack

Reputation: 66961

looks like you could use jna to tie into the "C" way of waiting for a pid to end (in windows, poll OpenProcess( PROCESS_QUERY_INFORMATION ...) to see when it reports the process as dead, see ruby's win32.c

Upvotes: 0

Sam
Sam

Reputation: 939

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.

Upvotes: 2

AaronM
AaronM

Reputation: 713

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.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272417

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.

Upvotes: 1

Related Questions