Java process when terminated abnormally with Kill or pkill unix comamnds doesnot delete temporary files

谁说我不能喝 提交于 2019-12-13 08:24:38

问题


When a tool developed in Java is launched, it creates temporary files in a folder. If terminated properly those files are getting deleted , but if terminated with kill or pkill commands those files are not getting deleted. Is there any way to send a signal to java process to delete those files before terminating the process? Please help me to solve this issue. Thanks in Advance


回答1:


You can add shutdown hook and clean everything you need explicitly.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { 
        //put your shutdown code here 
    }
});

This is actually the same what java.io.File#deleteOnExit does for you.




回答2:


It seems like File.deleteOnExit() is fragile when it comes to process termination. In contrast, using the NIO API with the StandardOpenOption.DELETE_ON_CLOSE seems to be more reliable even though it’s specification only says: “If the close method is not invoked then a best effort attempt is made to delete the file when the Java virtual machine terminates”

E.g. when running the following program:

File f1=File.createTempFile("deleteOnExit", ".tmp");
f1.deleteOnExit();
final Path f2 = Files.createTempFile("deleteOnClose", ".tmp");
FileChannel ch = FileChannel.open(f2, StandardOpenOption.DELETE_ON_CLOSE);
System.out.println(f1);
System.out.println(f2);
LockSupport.parkNanos(Long.MAX_VALUE);
// the following statement is never reached, but it’s here to avoid
// early cleanup of the channel by garbage collector
ch.close();

and killing the process while it hangs at parkNanos, the JVM leaves the deleteOnExit tmp file while correctly deleting the deleteOnClose file on my machine.



来源:https://stackoverflow.com/questions/26754424/java-process-when-terminated-abnormally-with-kill-or-pkill-unix-comamnds-doesnot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!