为什么在打开的文件上取消链接成功? [英] Why is unlink successful on an open file?

查看:122
本文介绍了为什么在打开的文件上取消链接成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么打开的文件被删除?在Windows Xamp上,我收到消息仍在工作",但在其他PHP serwer文件上,即使该文件已打开,我也收到了消息文件已删除".即使第一个脚本仍在工作,我也可以从FTP删除文件:(

<?php
$handle = fopen("resource.txt", "x");
sleep(10);
?>


<?php
if (file_exists("resource.txt") && @unlink("resource.txt") === false) {
    echo "still worning";
    exit;
}
else
    echo "file deleted";
?>

解决方案

UNIX系统通常允许您这样做,是的.底层C unlink函数记录如下:

unlink()函数从其目录中删除由path命名的链接 并减少该文件所引用的文件的链接计数 关联.如果该减量将文件的链接数减少为零,则 没有进程打开文件,然后与该文件关联的所有资源 被回收.如果一个或多个进程上次打开文件时 链接被删除,链接被删除,但是文件的删除是 直到所有对它的引用都被关闭为止.

换句话说,您基本上可以随时标记要删除的文件,但是只要应用程序仍在访问它,系统实际上就会保留它.只有当所有应用程序都放开了文件时,它才最终真正被删除. Windows显然不会那样进行. 更新:自PHP 7.3 现在可以unlink打开文件.

请注意,在多进程环境中,UNIX的行为是唯一明智的行为.如果您必须等待所有进程关闭对文件的访问,然后系统才能将其删除,则根本不可能删除经常访问的文件.是的,那是关于无法删除文件,仍在使用,请重试?" 的Windows对话框,从那里您将永远不会摆脱它.

Why open file is deleted? On Windows Xamp, I get message "still working", but on other PHP serwer file is deleted, even if it is open and I get message "file deleted". I can delete file from FTP too, even if first script is still working :(

<?php
$handle = fopen("resource.txt", "x");
sleep(10);
?>


<?php
if (file_exists("resource.txt") && @unlink("resource.txt") === false) {
    echo "still worning";
    exit;
}
else
    echo "file deleted";
?>

解决方案

UNIX systems typically let you do this, yes. The underlying C unlink function is documented as such:

The unlink() function removes the link named by path from its directory and decrements the link count of the file which was referenced by the link. If that decrement reduces the link count of the file to zero, and no process has the file open, then all resources associated with the file are reclaimed. If one or more process have the file open when the last link is removed, the link is removed, but the removal of the file is delayed until all references to it have been closed.

In other words, you can basically mark the file for deletion at any time, but the system will actually keep it around as long as applications are still accessing it. Only when all applications have let go of the file will it finally actually be removed. Windows apparently does not do it that way. Update: Since PHP 7.3 it's now possible to unlink open files.

As a side note, UNIX' behaviour is the only sane behaviour in a multi-process environment. If you have to wait for all processes to close access to a file before the system lets you remove it, it's basically impossible to remove frequently accessed files at all. Yes, that's where those Windows dialog boxes about "Cannot delete file, still in use, retry?" come from which you can never get rid of.

这篇关于为什么在打开的文件上取消链接成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆