开发者

Terminate process run with `exec` when program terminates

I have a java program that runs another (Python) program as a process.

Process p = Runtime.getRuntime().exec("program.py", envp);

If the java program finish processing, the Python process is finished as well. The fini开发者_JAVA百科sh command sends a signal to the Python process to close it.

In normal situation the process is closed this way:

BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
output.write("@EOF\n");
output.flush();

However, when the java program crashes, the process is not closed. The closing command is not send due to the crash. Is it possible to terminate the process automatically every time the program is terminated?


hey @czuk would a ShutdownHook hook be any use? This will deal with the following scenarios

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

When the system unexpectedly crashes this is not so easy to capture.

Perhaps use the Thread.setDefaultUncaughtExceptionHandler method?


Assuming that by crashing you mean that the Java program throws an exception, I would just kill the Python process when that happens. I haven't seen your code but:

class Foo {

    Process p;

    private void doStuff() throws Exception {
        p = Runtime.getRuntime().exec("program.py", envp);
        // More code ...
    }

    private void startStuff() {
        try {
            doStuff();
        } catch (Exception e) {
            p.destroy();
        }
    }

    public static void main(String[] args) {
        Foo foo = new Foo();
        foo.startStuff();
    }
}

Something like this should work if only exceptions that cause the program to crash escapes from doStuff().

Even if you don't expect the program to crash in this way when it is finished I think this approach is better than perhaps wrapping it in a shell script that in some way kill the Python process. Handling it in your program is less complex and it might even be a good idea to keep the code once the program is finished, since you might still have bugs that you don't know about.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜