Process termination is done with `exec` when the 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 processing of the finished java program terminates, the Python process also terminates. The finish command sends a signal to the Python process to close it.

In a normal situation, the process closes as follows:

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

However, when the java program crashes, the process does not close. A close command is not sent due to a failure. Is it possible to automatically terminate the process every time the program terminates?

+7
source share
2 answers

Assuming that when you crash, you mean that the Java program throws an exception, I would just kill the Python process when that happens. I have not 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 the exceptions due to which the program crashes with screens from doStuff() .

Even if you do not expect the program to crash when it is finished, I think this approach is better than possibly wrapping it in a shell script that will somehow kill the Python process. Processing it in your program is less complicated, and it’s even nice to save the code after the program ends, since you may have errors that you don’t know about.

+2
source

hey @czuk will use ShutdownHook ? This will apply to 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 method is called (equivalently, System.exit) or

  • A virtual machine terminates in response to a user interruption, for example, dials ^ C or a system-wide event, such as a user shutdown or system shutdown.

When the system crashes unexpectedly, it is not so easy to do.

Perhaps use the Thread.setDefaultUncaughtExceptionHandler method?

+3
source

All Articles