Search code examples
c++winapimsbuildcreatefile

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


I am debugging a custom exe during the compiling of my code using the msbuild exec task.

It runs the following code:

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 is the dll/exe that was compiled by msbuild, which is passed to program as an argument.

I am seeing the following error sometimes:

unable to open file (20)

After rebuilding the error doesn't happen again. According the the windows codes, error code 20 is:

ERROR_BAD_UNIT20 (0x14)

The system cannot find the device specified.

I'm not sure what this mean though. It doesn't seem to be that the file in question doesn't exist, because it does. If it didn't the error code would be "2", I've tried. Do you know what can cause this error? Thanks.

Couple of things:

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() just does a printf of the file name and message.


Solution

  • You're printing the error code in hexadecimal (%x) rather than in decimal.

    Error code 0x20 (32 decimal) is ERROR_SHARING_VIOLATION ("The process cannot access the file because it is being used by another process.") So, yes, your guess about another process having the file open was correct.

    In these circumstances, I suspect a race condition, possibly affected by virus scanning. Consider having your code detect this particular error and retry after a short wait.