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

北慕城南 提交于 2019-12-24 02:11:54

问题


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:


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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2218054/how-to-wait-for-a-process-to-end-in-java-or-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!