How do you gracefully exit a Process in Java? - java

I am trying to make a Java program which will run several other unrelated Java programs, specifically a Minecraft server.
Currently, I am trying to work out how to end a java.lang.Process gracefully.
This is the code for my spawner program:
http://dl.dropbox.com/u/26746878/SpawnerSource/Main.java.txt
And this is the code for the program which is spawned:
http://dl.dropbox.com/u/26746878/SpawnerSource/Tester.java.txt
What I do is run my spawner program. Then, after a few seconds, I terminate it with Ctrl-C.
What I want to see is my program output 'Shutting Down' followed by 'Ending'. I also want to see a file 'test.txt'.
What I actually see is only 'Shutting Down', with no 'Ending' nor 'test.txt'
I believe the problem is that Process.destroy() is forcefully ending the process without letting the shutdown hooks run.
Is there an alternative to Process.destroy() which will exit the process gracefully (ie: as if I had pressed Ctrl-C)?

You should never destroy a working process as it might get the whole OS into an unstable state (believe me, this caused us 2 hours downtime and cost 10000$ to my company :( )
What you should do instead is as #Kane mentioned, send a shutdown request to all your child processes and wait until they are all finished (every child process sends an RMI notification back to the main process right before gracefully exiting)
class ParentProcess{
Map<int, CountDownLatch> finishSignals = new ConcurrentHashMap<int, CountDownLatch>();
public void startProcess(){
// Start child process
// get its ID
// and create a count down latch for it
finishSignals.add(processId, new CountDownLatch(1));
}
public void shutDownProcess(processId){
// Send an RMI request to process ID to shutdown
}
// RMI request sent from child process before stopping
public void processFinishedNotification(processId){
finishSignals[processId].countDown()
}
public void waitForChildsToFinish(){
// This for loop will block until all child processes have sent a finish notification
for(CountDownLatch childFinishSignal : finishSignals){
childFinishSignal.await();
}
}
}

You may want to look into Remote Method Invocation, and have your spawner process ask the child processes to shut themselves down instead of having the spawner process kill the child processes itself.

Related

Avoid QProcess being killed (QProcess: Destroyed while process is still running)

I tried to run this code:
QProcess process;
process.setWorkingDirectory("D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target");
process.setProgram("java.exe");
process.setArguments({"-jar","StackExp-1.0-SNAPSHOT.jar"});
process.start();
and cmd won't open, and doesn't execute. It just shows this message:
QProcess: Destroyed while process ("java.exe") is still running
Please, who knows what's wrong? And how can I run my .jar file using cmd in QProcess?
You are probably calling the destructor of QProcess before it is finished, which kills the process as mentioned in the docs. Note that the destructor is called when process goes out of scope.
Different solutions exists:
Wait for process to finish: waitForFinished
process.waitForFinished (-1); // -1 = no time out
Construct QProcess on the stack
QProcess *process = new QProcess();
...
Note that you should destruct the process after it is finished to avoid a memory leak. Specifying a parent during construction may be useful to automatically manage the lifetime of QProcess.
Start the process in detached mode: startDetached
...
process.startDetached ();
If the calling process exits, the detached process will continue to run unaffected.
One could also use the static overload of QProcess::startDetached.

Running process from cmd.exe process inside thread executor service does not delete terminated processes

I have a program that creates a lot of information and I take that information and throw it into a thread by way of
final static ExecutorService service = Executors.newFixedThreadPool(10);
and pass it information via:
service.submit(new threadTry(str));
Where threadTry is the thread that takes the information, passes it inside command line arguments to generate a command, executes the command, then the cmd process runs the next process if criteria met.
Then the Executor service takes the list of submitted jobs, runs the 10 threads I've limited it to with the information given to them, creates a process which runs a command line window which can pop up another if a certain criteria is met. The command line window and the additional window that pops up do in fact terminate and the thread containing the command line window does terminate as well. The ExecutorService starts another thread with another bit of information. However, The cmd.exe and the other program are listed in windows 7 resource monitor as terminated. My program generates between 150-250 of these terminated cmd's/second (The handles to the javaw.exe process goes up and up with this). Only after I forcibly stop the main program, all the terminated processes are released.
My main problem is that I have to pass so much information that my program gets to about 56% done, then halts. I assume this is because the operating system cannot keep track of so many processes (even though they are terminated, but still listed). Halting is not caused by main program, it generates all information and terminates within 2 seconds (without doing anything with the info). With the processing of the information, my program takes about 2-3 hours to get to 56%.
public class threadTry extends Thread {
String str="";
public threadTry(String str){
this.str=str;
}
public void run(){
try{
String[] cmd={"...",str,"..."}; //input many arguments into cmd
ProcessBuilder probuilder= new ProcessBuilder( cmd );
Process process = probuilder.start();
if(!process.waitFor(5, TimeUnit.SECONDS)){//if we wait longer than 5 seconds,
//then print this message (this is the standard wait for the process that
//waits until termination)
System.out.println(str+": has exited with thread: "+this.getId());
}
int exitValue = process.exitValue();
if(exitValue!=3){
System.out.println("---------------------------------------------------");
System.out.println("\n\nExit Value is " + exitValue+" For: "+str);
System.out.println("---------------------------------------------------");
}
process.destroyForcibly();//does nothing to help clear the already
//terminated process
}catch(Exception e){
e.printStackTrace();
}
}
}

Remove Shutdown Hook of another Java process [duplicate]

How do you handle clean up when the program receives a kill signal?
For instance, there is an application I connect to that wants any third party app (my app) to send a finish command when logging out. What is the best say to send that finish command when my app has been destroyed with a kill -9?
edit 1: kill -9 cannot be captured. Thank you guys for correcting me.
edit 2: I guess this case would be when the one calls just kill which is the same as ctrl-c
It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.
The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.
Registers a new virtual-machine shutdown hook.
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.
I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, as expected. On a kill -15 it DOES run the shutdown hook every time.
public class TestShutdownHook
{
public static void main(String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
#Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
while (true)
{
Thread.sleep(1000);
}
}
}
There isn't any way to really gracefully handle a kill -9 in any program.
In rare circumstances the virtual
machine may abort, that is, stop
running without shutting down cleanly.
This occurs when the virtual machine
is terminated externally, for example
with the SIGKILL signal on Unix or the
TerminateProcess call on Microsoft
Windows.
The only real option to handle a kill -9 is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps command looking for your program in the list and act accordingly when it disappeared.
#!/usr/bin/env bash
java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"
I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).
This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.
But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).
As other users commented, the usage of shutdown hooks seems mandatory.
So, how do I would handle it?
Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).
As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.
So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread th : runningThreads) {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.getClass().getName().startsWith("org.brutusin")) {
System.out.println("Interrupting '" + th.getClass() + "' termination");
th.interrupt();
}
}
for (Thread th : runningThreads) {
try {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.isInterrupted()) {
System.out.println("Waiting '" + th.getName() + "' termination");
th.join();
}
} catch (InterruptedException ex) {
System.out.println("Shutdown interrupted");
}
}
System.out.println("Shutdown finished");
}
});
Complete test application at github: https://github.com/idelvall/kill-test
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
You can use Runtime.getRuntime().addShutdownHook(...), but you cannot be guaranteed that it will be called in any case.
Reference https://aws.amazon.com/blogs/containers/graceful-shutdowns-with-ecs/
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("TERM"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.
Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.

Calling Method at the End of Program Execution

I am creating a client library for an API endpoint using Unirest to simulate GET and POST requests. Once the program finishes, the following code must be called in order to terminate the current thread.
Unirest.shutdown(); // must be called in order to clear the high CPU consuming thread
Is there any possible way implicitly call this in my client library at the end of the program's execution?
Yes - your best option is likely a Shutdown Hook. It will be called/executed when the JVM is terminating. As an example:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
System.out.println("JVM shutting down, closing Unirest");
Unirest.shutdown();
}
}));
You should ideally call the addShutdownHook() method as soon as possible, after you have started the Unirest service.

Shutdown spawned java child process gracefully

I use ProcessBuilder to spawn a child process for executing writing some data to file system. And a problem occurs because the parent process may crash/ killed unexpectedly, the child process just hangs even I use e.g. jps checking if its parent process dies then exits. What is the right way for a spawned child process to detects if its parent process is dead and then exit?
Also, After searching on the internet, most solution use Runtime.addShutdownHook(), but this is not provided in ProcessBuilder. Does it have equivalent one?
You did a good search around the problem. So you may want to use the returned reference to the Process instance and the Runtime.addShutdownHook(Thread) method you mentioned. This is the last step that I believe you need to take:
List commands = new ArrayList();
commands.add("xeyes"); // launch this command
ProcessBuilder pb = new ProcessBuilder(commands);
final Process p = pb.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
p.destroy();
}
});
Thread.sleep(2000); // sleep for some time
In a similar situation I implemented a heartbeat mechanism where the parent process had to regularly send heartbeats. If that did not happen the child process would shut itself down.

Categories