原子创建文件的最佳方法
以原子方式创建新文件的“最佳实践”(据我所知)是打开一个临时文件(使用 tmpfile()),然后将文件移动到其最终位置。
但是,如果临时文件位于不同的安装点上,这将无法正常工作,因为这将导致文件逐渐累积,并额外导致不必要的 IO 开销。
另一种选择是在与最终目标相同的目录中创建一个临时文件,但这具有为用户创建不寻常文件的缺点(MS Word 和 ViM 等应用程序会这样做,但我也认为这种行为不好)。
是否有与 tmpfile() 类似的方法允许我指定挂载点?我意识到这可能不存在于 PHP 中,因此 Posix/C 函数或 shell 调用也是可以接受的。
The 'best practice' (as I see it) to atomically create a new file, is to open a temporary file (using tmpfile()), and then moving the file to it's final location.
However, this won't work well if the temporary file is on a different mountpoint, as this will result in the file gradually building up and additionally result in unneeded IO overhead.
Another option is to create a temporary file in the same directory as the final destination, but this has the disadvantage of creating a unusual file for a user (Apps such as MS Word and ViM do this, but I also consider this bad behaviour).
Is there a similar method as tmpfile() that will allow me to specify the mountpoint? I realize this probably doesn't exist built-into PHP, so a Posix/C-function or shell-call is also acceptable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,POSIX 堆栈中没有这样的方法。 tmpfile() 和 tmpname() 用于普通临时目录。有 tempnam(),您可以在其中指定目标目录对于临时文件。但这基本上是实现您描述的第二个选项的一种方法。
No, there isn't such a method in the POSIX stack. tmpfile() and tmpname() use to normal temp dir. There is the tempnam(), where you can specific the target directory for the temp file. But is is basically a way to implement the second option you described.
为
qmail
开发的 maildir 协议为多个写入者到同一目标目录,甚至跨 NFS。在此方案中,保证“tempfile”目录与目标目录位于同一文件系统上。该算法可以在高效的 shell 实用程序
safecat
,其联机帮助页将算法描述为:The maildir protocol developed for
qmail
provides safe file creation for multiple writers to the same target directory, even across NFS. In this scheme, the "tempfile" directory is guaranteed to be on the same filesystem as the target dir.The algorithm is conveniently implemented in an efficient shell utility,
safecat
, whose manpage presents the algorithm as:当您谈论“挂载点”时,我假设您处于类 UNIX 环境中。
也许您可以将其视为一种解决方法或不良行为,但我认为在同一目标文件夹上创建隐藏(.tmpfile)临时文件是可以接受的。
当然,如果您不想在目标目录中看到任何虚假文件,您当然可以在适合此任务的应用程序无法访问的同一安装点上创建一个特定文件夹,以这种方式在同一安装点上模拟 tempfile() 。
As you are talking about the "mountpoint" I'm assuming you are on a unix-like environment.
Maybe you can consider it a workaround or bad-behavior, but I think creating an hidden (.tmpfile) temp file on the same destination folder could be acceptable.
You can of course create a specific folder on the same mount point not accessible to the application suited for this task, simulating this way a tempfile() on the same mountpoint, if you don't want to see any spurious file in the destination dir.
我必须做这样的事情并使用 MySQL 数据库。只是将我需要的信息存储在表中,完成后我删除了该记录。只是一个想法:)
I had to do something like this and went with a MySQL DB. Just stored the info I needed in a table and when I was finished I just deleted the record. Just a thought :)