2

I have a Java application running on a linux server. When it started, it recorded the process id to a "pidfile".

When I close it, I simply read the pid from that file, and kill it:

kill -9 12345

But other people says it is not safe, instead, they suggest me to embed a small http server, and provide a http api for closing, such as:

http://localhost:8080/close

When I want to close it, I need to visit it:

curl http://localhost:8080/close

It works but very boring, I still prefer the "process id" way. Is there any way to use process id to close the application safely?


Update:

"Safely" here I mean I can cancel some running tasks which may writing files to disk and close some resources before exiting.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 2
    Depends on what you mean by safely? I guess "people" are saying that to allow the Java process to clean up and close resources, but if that's not relevant for you, then don't bother (although `kill -HUP` might be a little nicer...) – Anders R. Bystrup Nov 15 '13 at 09:30

1 Answers1

1

You can shut it down by executing kill -HUP processId

If there is a need to gracefully finalize work, register your shutdown hook and perform all required finalization there.

More info here Runtime.addShutdownHook

P.S: In my opinion, do not embed web server just for this purpose if you do not really need it. And if you use web server, you need also think about security - anyone who knows the url, can shut your app down remotely:)

Vasyl Keretsman
  • 2,688
  • 2
  • 18
  • 15
  • Shutdown hooks were discussed in a related post: http://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully – Axel Kemper Nov 15 '13 at 09:41
  • I see some documents say that `kill -HUP` means restarting an application. But I don't want it "restarting", just close it. Do I misunderstanding anything? – Freewind Nov 15 '13 at 09:56
  • 1
    The application may do arbitrary things as reaction on a signal which does not kill it right away. HUP stands for hang-up, i.e. the connection to the user is lost. This normally leads to a graceful quit. The signals are explained here: http://en.wikipedia.org/wiki/Unix_signal – Axel Kemper Nov 15 '13 at 10:39
  • @Freewind, just to add a little bit to what Axel said - your app receives the KILL signal, and reacts on it - in your case "cancel some running tasks which may writing files to disk and close some resources before exiting" and terminates. – Vasyl Keretsman Nov 15 '13 at 11:47