2

So i have my program, but i don't want it to be able to be closed. I know its not possible to make it 100% unclosable but this method seems like it would work the best.

I realize that you can addShutdownHook, but this will not work if the process is killed in from the operating system, using Task Manager (Windows) or kill -9 (Unix). Obviously, if I have a second process running and the main one is killed it can just re-run the main one again, which makes it much more reliable.

So, I want to know how to create a watchdog process in Java that monitors my actual Java application to detect if it has been closed, then if it has been closed it re-executes the program.

Community
  • 1
  • 1
Hugh Macdonald
  • 143
  • 1
  • 12

2 Answers2

1
  1. Your application program could periodically update a file. The watchdog could check whether that file has been updated recently; if it has not, the watchdog would conclude that the application program has exited, and restart it. The application program could do the updating in a separate daemon thread, to ensure the updates occur regardless of the application load. This can be done using standard Java and so is very portable.

  2. Another option is for the application program to find its own process ID (PID), when it starts running, and write that into a file. The watchdog program reads that file to find the PID of the application. It can then periodically examine the list of running processes to check that the application program is still among them. This is more complicated and uses some non portable code. But it can be made to integrate better with the conventional manner of starting and stopping you application program as a daemon on Unix computers, because such daemons conventionally write their PID into a file anyway.

  3. You have specified that the watchdog program must be in Java. If you run it on Unix and you are willing to write it as a shell script, it can be written very easilly, and a manner that will avoid the problems of using PID files and scanning the process list.

Community
  • 1
  • 1
Raedwald
  • 46,613
  • 43
  • 151
  • 237
1

Make a wrapper "bouncer" script/app based on the exit code logic. Make it positive or negative as needed.

The below Bash example assumes the application should be restarted when it exists with 42 status.

#!/bin/bash

code=42
while (( code == 42 )); do
  myapp
  code=$?
done

The identical wrapper can be done in Java using the ProcessBuilder

bobah
  • 18,364
  • 2
  • 37
  • 70