How to NOT prevent the device from being removed / removed safely?

How can I get a HANDLE to a file * on any device and not prevent the user from pulling out the device?

I tried calling CreateFile (and even NtCreateFile ) with the most liberal access I can think of, i.e. FILE_READ_ATTRIBUTES for access, and FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE to access permissions, but it still does not work.

( FileTest is a great tool to test this without writing a program.)


* Update:

I would really like the decision to work with descriptors on volumes or disks (and not just files) - I mean as \\.\D: or \\.\PhysicalDrive0 . But if there is no such solution, then file accesses will also be useful.

+4
source share
2 answers

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!

+2
source

You can not.

But you can follow the message of the extraction device, and then close all the pens you have.

Device Events (MSDN)

+2
source

All Articles