gpt4 book ai didi

php - 为什么在 Windows 中可能会尝试删除一个文件两次?

转载 作者:可可西里 更新时间:2023-11-01 11:27:19 25 4
gpt4 key购买 nike

我一直在努力尝试用 PHP 为我开发的 Windows 机器编写一个持续集成脚本。

克隆了一个 Git 存储库后,我无法制作一个脚本来删除它。 (.git 文件夹和其中的所有内容)。我收到“权限被拒绝”错误。

似乎断断续续。我试过 Phing,但失败了,但引导我到 this Phing ticket ,所以我并不孤单 - 但使用 attrib 的解决方案对我不起作用。

我终于意识到,只需尝试两次即可删除其中的某些文件夹和/或文件。所以我最终起作用的 PHP 代码是这样的:

<?php
function delTree($dir, $ignore = array()) {

// no need to continue if $dir doesn't exist
if (!file_exists($dir))
return true;

// must not continue if it's a link. trigger an error.
if (is_link($dir)) {
trigger_error("Cannot delete $dir: it's a link.", E_ERROR);
return false;
}

// if it's a file, delete it and return.
if (is_file($dir)) {
return tryUnlink($dir, 2);
}

// it's a directory. so...
// build an array of files/directories within it to delete
$files = array_diff(
scandir($dir), array('.', '..'), $ignore
);

// delete each directory within $dir
foreach ($files as $file) {
delTree("$dir/$file", $ignore);
}

// delete $dir itself
return tryRmdir($dir, 2);
}
function tryUnlink($file, $attempts = 2){
$result = unlink($file);
if (!$result) {
if ($attempts > 1){
return tryUnlink($file, $attempts--);
} else {
trigger_error("Cannot delete file $file", E_ERROR);
return false;
}
}
return true;
}

function tryRmdir($dir, $attempts = 2){
$result = rmdir($dir);
if (!$result) {
if ($attempts > 1){
return tryRmdir($dir, $attempts--);
} else {
trigger_error("Cannot delete directory $dir", E_ERROR);
return false;
}
}
return true;
}

并通过将 $attempts 参数设置为 2 调用它们解决了所有问题(12 小时后)。

我尝试过诸如chmod将文件更改为0666、关闭IDE、关闭SourceTree、任何打开的资源管理器窗口、戴着锡纸帽,甚至使用如下命令调用 exec():

rm -r .git -Force
rmdir .git /s /q

现在可能还有 10 个埋在我的仓库中的某个地方。

可能是什么原因?

最佳答案

tryUnlink()tryRmdir() 这两个函数将导致无限循环(除非它实际上被删除)。查看以下代码片段 + 输出。

代码:

<?php

function foo ($attempts = 2) {
echo "attempts = $attempts\n";
if ($attempts > 1) {
foo ($attempts--);
} else {
echo "returning with \$attempts <= 1\n";
}
}
foo(2);

输出:

attempts = 2
attempts = 2
attempts = 2
[...many many many dupes...]
attempts = 2
attempts = 2
attempts = 2
Segmentation fault (core dumped)

鉴于没有说删除会在第二次运行时开始。

关于php - 为什么在 Windows 中可能会尝试删除一个文件两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944663/

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