8

I have a Java application with a shutdown hook. The shutdown hook is executed when I run the application in IntelliJ and click on the Exit button (as opposed to the Stop button which does not result in the shutdown hook).

I need to be able to shutdown the process from a Windows batch file. I have tried various combinations of the taskkill command without luck (assuming a PID of 1234):

taskkill /pid 1234 /t
taskkill /pid 1234 /f /t

Is there a way for me to terminate a Java process from an MS batch file, and have the Java shutdown hooks be executed?

The application runs on a Windows server.

vegemite4me
  • 6,621
  • 5
  • 53
  • 79
  • 1
    maybe this will help https://stackoverflow.com/questions/813086/can-i-send-a-ctrl-c-sigint-to-an-application-on-windows – loadingnow Mar 25 '20 at 05:48
  • Does `taskkill /pid 1234` without `taskkill /pid 1234 /f /t` not close the program or not close it gracefully? If you run the second command right after the first, Java does not have enough time to gracefully exit before being killed. I.e. `taskkill` without `/t` or `/f` just sends a `WM_CLOSE` message, it does not wait for the message to be processed or for process to terminate. I'm not sure if JMX will be of use to you: https://docs.oracle.com/javase/1.5.0/docs/guide/management/overview.html example: https://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully#208809 – Jack White Mar 06 '21 at 11:45
  • shutdown hooks are not guaranteed to execute, and usually do not. your best bet is to gracefully shutdown by programatically shutting down your service or perhaps calling `System.exit()`, based on some external stimulus (create and call a shutdown API, give your app a poison pill, check for presence of kill file on disk, whatever) – Bohemian Mar 10 '22 at 23:24

2 Answers2

0

I might be a little late with this but better late than never I guess. My idea and take at this would be to use a "Hybrid Batch" which was discussed here. And with that it would be possible to work with VBS to do that. Such approaches were discussed here or here. Through that it should be possible to trigger the shutdown hooks as opposed to a pure batch approach like before. But as I didnt test this myself, I could be absolutely wrong with this as in that it also doesnt work.

ouflak
  • 2,458
  • 10
  • 44
  • 49
-1

You should try this:

1 Go to command line. 2 tasklist.

C:\Users\HD> for /f "tokens=1" %i in ('jps -m ^| find "JAVA_PROCESS_NAME"') do ( taskkill /F /PID %i ) l /F /PID %i ) C:\Users\HD> (taskkill /F /PID 5076 )