Search code examples
cwindowswinapistdiocreatefile

Exclusive volume opening


I can open a volume "exclusively" with CreateFile by setting dwShareMode to 0:

#include <windows.h>
int main() {
  HANDLE ki = CreateFile("\\\\.\\F:", GENERIC_READ | GENERIC_WRITE, 0,
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
}

I can open a volume in "shared mode" with fopen:

#include <stdio.h>
int main() {
  FILE* ki = fopen("\\\\.\\F:", "r+b");
}

I can open a file "exclusively" with open:

#include <stdio.h>
#include <fcntl.h>
int main() {
  int ju = open("lima.txt", O_RDWR | O_EXCL);
  FILE* ki = fdopen(ju, "r+b");
}

However if I try to open a volume with open, it will fail:

#include <stdio.h>
#include <fcntl.h>
int main() {
  int ju = open("\\\\.\\F:", O_RDWR | O_EXCL);
  FILE* ki = fdopen(ju, "r+b");
}

After testing, this happens with or without the O_EXCL flag. Is exclusive volume opening something that can only be done with CreateFile, or am I missing something?


Solution

  • According to the standard:

    result is undefined if O_RDWR is applied to a FIFO

    It appears that a volume is recognized as a FIFO in this situation. To fix:

    open("\\\\.\\F:", O_RDONLY);
    

    Or:

    open("\\\\.\\F:", O_WRONLY);
    

    Or:

    open("\\\\.\\F:", O_RDONLY | O_WRONLY);