gpt4 book ai didi

c++ - DropBox 会干扰 DeleteFile()/rename()

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:42 25 4
gpt4 key购买 nike

我有以下代码,每两次执行一次全天分钟:

int sucessfully_deleted = DeleteFile(dest_filename);

if (!sucessfully_deleted)
{
// this never happens
}

rename(source_filename,dest_filename);

每隔几个小时,rename() 就会失败一次,errno=13 (EACCES)。涉及的文件都位于 DropBox 目录中,我有一种预感,DropBox 可能是原因。我认为 DeleteFile() 函数可能会返回一个非零的 successfully_deleted ,但实际上 DropBox 可能仍然忙于做一些与删除相关的事情,从而阻止 rename() 成功。我接下来要做的是将 rename() 更改为 my_rename() ,这将尝试 rename() 并且在任何失败时都会 Sleep() 一秒钟并尝试第二次。果然从那以后就一直运行良好。此外,我每隔几个小时就会收到一条显示首次尝试失败的诊断消息。第二次尝试从未失败。

所以你可以说问题已经完全解决了......但我想了解可能发生的事情,以便在未来更好地保护自己免受任何相关的 DropBox 问题......

真的,我想要一个新的 super_delete() 函数,该函数在文件被正确删除并在所有方面完成之前不会返回。

最佳答案

在windows下要求删除文件真的从不删除文件而已。它用特殊标志 (FCB_STATE_DELETE_ON_CLOSE) 标记它 FCB(文件控制 block )。真正的删除只有在最后一个文件句柄关闭时才会发生。

The DeleteFile function marks a file for deletion on close. Therefore, the file deletion does not occur until the last handle to the file is closed. Subsequent calls to CreateFile to open the file fail with ERROR_ACCESS_DENIED.

如果存在部分(内存映射文件)在文件上打开 - 文件甚至不能被标记为删除。 api 调用失败,返回 STATUS_CANNOT_DELETE。所以一般不可能总是删除文件。

如果存在另一个打开的文件句柄(但不是部分!),从 Windows 10 rs1 开始存在新的删除功能 - FileDispositionInformationExFILE_DISPOSITION_POSIX_SEMANTICS .在这种情况下:

Normally a file marked for deletion is not actually deleted until all open handles for the file have been closed and the link count for the file is zero. When marking a file for deletion using FILE_DISPOSITION_POSIX_SEMANTICS, the link gets removed from the visible namespace as soon as the POSIX delete handle has been closed, but the file’s data streams remain accessible by other existing handles until the last handle has been closed.

ULONG DeletePosix(PCWSTR lpFileName)
{
HANDLE hFile = CreateFileW(lpFileName, DELETE, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT, 0);

if (hFile == INVALID_HANDLE_VALUE)
{
return GetLastError();
}

static FILE_DISPOSITION_INFO_EX fdi = { FILE_DISPOSITION_DELETE| FILE_DISPOSITION_POSIX_SEMANTICS };

ULONG dwError = SetFileInformationByHandle(hFile, FileDispositionInfoEx, &fdi, sizeof(fdi))
? NOERROR : GetLastError();

// win10 rs1: file removed from parent folder here
CloseHandle(hFile);

return dwError;
}

关于c++ - DropBox 会干扰 DeleteFile()/rename(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687370/

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