CreateFileA returns 错误 20,"The system cannot find the device specified" 间歇性

CreateFileA returns error 20, "The system cannot find the device specified" intermittently

我正在使用 msbuild exec 任务编译我的代码期间调试自定义 exe。

它运行以下代码:

HANDLE hFile = CreateFileA(szFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
  Fatal(szFile, 1, "unable to open file (%x)", GetLastError());

szFile是msbuild编译的dll/exe,作为参数传给程序

我有时会看到以下错误:

unable to open file (20)

重建后错误不再发生。根据windows代码,错误代码20是:

ERROR_BAD_UNIT20 (0x14)

The system cannot find the device specified.

虽然我不确定这是什么意思。似乎有问题的文件不存在,因为它确实存在。如果不是,错误代码将是“2”,我试过了。你知道什么会导致这个错误吗?谢谢。

两件事:

const char *szFile = nullptr;
...
szFile = argv[i]; // it loops over the arguments, parses them and finds the right argment for the file.
....
SetFileAttributes(szFile, FILE_ATTRIBUTE_NORMAL);
HANDLE hFile = CreateFileA(szFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
   Fatal(szFile, 1, "unable to open file (%x)", GetLastError());

Fatal() 只是打印文件名和消息。

您正在以十六进制 (%x) 而不是十进制打印错误代码。

错误代码 0x20(十进制 32)是 ERROR_SHARING_VIOLATION("The process cannot access the file because it is being used by another process.")所以,是的,您对打开文件的另一个进程的猜测是正确的。

在这些情况下,我怀疑存在竞争条件,可能受病毒扫描影响。考虑让您的代码检测到此特定错误并在短暂等待后重试。