简体   繁体   中英

When I run Java from a batch file, can I hook a batch file to force exit?

I create a directory in a Java file and delete it when done.

If I quit during Java work, of course it will not perform the deletion.

I've used addShutdownHook() but it seems to work fine with a shutdown command.

My forced shutdown means when i closing the running batch file window. (:when push X button)

Is there a way to solve it in Java source?

It is my tried source

.
.
.
Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    FileUtils.deleteQuietly(new File(basePath));
                }
            });
.
.
.

I can not think of a pure java solution. The problem is, if your program is forced to shutdown, eg with kill -9 (SIGKILL), there is no chance for your program to hook in between. It will shutdown immediately.

You could use monitoring tools like monit or deamontools or supervisord to perform clean-up operations as soon as your program has been shutdown.

You can also provide a handmade solution like suggested here: Shell Script For Process Monitoring , eg using tools like watch .

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