gpt4 book ai didi

windows - 删除使用 TempFile 创建的锁定文件

转载 作者:IT王子 更新时间:2023-10-29 02:35:27 26 4
gpt4 key购买 nike

我有一个 GUI (lxn/walk) 应用程序修补程序,它通过 ftp 下载文件,将其流式传输到临时文件并提取内容以更新本地文件。删除文件命令被推迟。

除非用户在下载文件时退出程序,否则文件不会被删除。

我试图通过捕获信号并删除那里的文件来正常退出来解决这个问题。但不幸的是,它抛出一个错误,该文件无法删除,因为它正在被另一个程序使用。这是有道理的,因为另一个程序本身实际上仍在写入临时文件。

现在我卡住了,不知道该怎么做才能确保临时文件在修补程序未运行时自动消失。我该如何正确地做到这一点?

该文件也可以创建为普通文件,而不仅仅是临时文件。我也想问一下,windows中哪里写临时文件最好?

最佳答案

Now I’m stuck and don’t know what to do to make sure that the temporary file is automatically gone once the patcher is not running. How do I do that correctly?

没有保证的方法可以完成此操作,因为应用程序无法控制的许多事情都可能导致它退出。由于某些硬件问题导致的电源故障或内核 panic 可能导致机器崩溃或强制重启。

一种常用的策略是在程序启动时检查上一次运行的状态。一些应用程序在启动时创建一个锁定文件,并在正常退出时将其删除。如果程序重新启动时此锁定文件存在,则意味着上一次运行没有导致干净退出,应用程序可以采取任何纠正措施。要采取的确切操作取决于应用程序的性质,有些拒绝启动,有些则向用户发出警告。

I would just like to ask too, where in windows is best to write a temporary file?

每个操作系统都有自己的临时文件位置。如果您消除 TempFiledir 参数,它将在适当的位置创建它,如 documentation 中所述:

TempFile creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, TempFile uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.

来自 os.TempDir我们看到以下内容:

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessible permissions.

关于windows - 删除使用 TempFile 创建的锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com