9

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.

3
  • 1
    maybe this will help stackoverflow.com/questions/813086/… Commented Mar 25, 2020 at 5: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: docs.oracle.com/javase/1.5.0/docs/guide/management/… example: stackoverflow.com/questions/191215/… Commented Mar 6, 2021 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) Commented Mar 10, 2022 at 23:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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 )

1 Comment

How is this different from my attempts above? I already know what the PID is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.