It should be clear that getting the file descriptor when installing the volume is trivial.
What happens when the volume turns off? All file descriptors become invalid. Attempts to use them return errors.
These pieces of code force-dismantle so that subsequent code can do direct I / O on it. This is an excerpt from a disk cleanup utility (a mass consumer product) that I wrote several years ago.
char fn [20]; sprintf (fn, "\\\\.\\%s:", vol -> GetVolName ()); vol_lock_handle = CreateFile (fn, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING | FILE_FLAG_RANDOM_ACCESS, NULL); fprintf (stderr, "Warning: volume dismount will disrupt or kill all processes with open files!\n" "Before confirming, verify no critical processes have open files on volume %s:\n" " Are you sure you want to dismount this volume? ('YES' to proceed)? ", g_vol -> GetVolName ()); char buf [30]; if (!fgets (buf, sizeof buf, stdin) || stricmp (buf, "yes\n")) { fprintf (stderr, " Volume dismount not confirmed--canceled.\n"); continue; } DWORD status; if (!DeviceIoControl (vol_lock_handle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &status, NULL)) { DWORD err = GetLastError (); fprintf (stderr, "Error %d attempting to dismount volume: %s\n", err, w32errtxt (err)); }
I understand how this code looks. For dismounting, the GENERIC_READ descriptor is obtained, then the volume is locked, and then written to. He works!
source share