简体   繁体   English

如何在退出时删除/取消链接文件

[英]How to delete/unlink a file on exit

How do I make, in Node, so that when the process is terminated or when the execution is halted a certain file I open with fs.openSync(filename, 'w'); 我如何在Node中进行创建,以便在进程终止或中止执行时,使用fs.openSync(filename, 'w');打开某个文件fs.openSync(filename, 'w'); is deleted/unlinked? 被删除/取消链接?

On windows, If I create the file and then I call fs.unlinkSync(filename); 在Windows上,如果我创建文件,然后调用fs.unlinkSync(filename); right after, the other program can see the file. 之后,其他程序可以看到该文件。 Additionally, when the program that created it terminates, the file is also gone. 此外,当创建它的程序终止时,该文件也消失了。

On Linux, the above is not true because after I unlink it, when the other tries to check the existence of the file it cannot find it in any shape or form I know of. 在Linux上,上述情况是不正确的,因为在我取消链接后,当另一个尝试检查文件是否存在时,它找不到我所知道的任何形状或形式。
Locks are not enforced unless the drive is mounted in a specific way. 除非以特定方式安装驱动器,否则不会强制执行锁定。
If I try to find a way to call fs.unlinkSync(filename); 如果我试图找到一种方法来调用fs.unlinkSync(filename); in callbacks either to SIGINT , SIGTSTP , etc... I always find a way to stop the program without the file being gone afterwards. 在对SIGINTSIGTSTP等的回调中……我总是找到一种方法来停止程序,而不会再丢失文件。

Please help me finding a way to create such file where being there is directly related to those files being in use. 请帮助我找到一种创建此类文件的方法,其中该文件与正在使用的文件直接相关。

(please ignore good practices and conventions, for now). (请暂时忽略良好做法和惯例)。

Consider a shell script like: 考虑如下的shell脚本:

#!/bin/sh

trap '' INT HUP TERM

read fname
read dummy

[ -f "$fname" ] && rm -f "$fname"

If you use popen(3) (or Node's equivalent) to open a pipe to that script, write a pathname on the pipe, and then do nothing else to that pipe , when your application exits, the invoked script will delete the file, having seen EOF on the "read dummy" line, because your app's exit will have closed the pipe to the invoked script. 如果使用popen(3) (或Node的等效项)打开该脚本的管道,请在该管道上写一个路径名,然后对该管道不做任何其他操作 ,当应用程序退出时,调用的脚本将删除文件,在“读取虚拟”行中看到EOF,因为您的应用程序退出将关闭通往被调用脚本的管道。

I've seen similar approaches used from Java apps that really want to see some temporary directory hierarchies cleaned up on JVM exit: have the helper script do it. 我已经看到Java应用程序使用了类似的方法,这些方法实际上是希望在JVM出口上清除一些临时目录层次结构:让帮助程序脚本执行此操作。 Just make sure that the pipe to the helper is not closed while your main application runs. 只需确保在您的主应用程序运行时未关闭通往帮助器的管道。

This likely fits your "ignore good practices and conventions" suggestion... 这可能符合您的“忽略良好做法和惯例”的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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