Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 finish 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?

like image 295
czuk Avatar asked May 13 '11 07:05

czuk


1 Answers

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?

like image 178
Paul Whelan Avatar answered Sep 28 '22 16:09

Paul Whelan