简体   繁体   中英

How do you tell when a program is being terminated?

So I'm working on a command-line server program that has to handle user stats and other data, and I have a command to stop the server and save user stats and the data to a file. What I want to know is if there is a way to also save user stats and data when the server is terminated without using the stop command. I tried creating a new process and finding when the process is terminated, but it didn't tell me when the server was being terminated. Is there any solution?

I assume you're talking about a situation where someone Ctrl+C 's the program, or terminates the program in an unexpected way. The best way I know to handle this situation is to use a Shutdown Hook .

From the documentation:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently

But there's a chance this won't work for you because as the documentation also says:

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 virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM