How can I prevent disc ejection during surgery on Mac OS X?

I have a multi-year task that performs a series of file operations on connected USB drives, and I want users to not unload the disk from the Finder (or anywhere else) when this happens. There is a Cancel button that allows you to complete the task at any time.

I suggested that keeping the file handle open on the mounted volume for the duration of the task will be a trick, but it did not work.

This is what I tried (error handling removed):

NSString *tempFilePath = @"/Volumes/myVolume/.myTempFile"; if ([[NSFileManager defaultManager] fileExistsAtPath:tempFilePath] == NO) { [[NSFileManager defaultManager] createFileAtPath:tempFilePath contents:nil attributes:nil] } _tempFile = [NSFileHandle fileHandleForWritingAtPath:tempFilePath]; 

Any ideas on what I can do to prevent a volume leak?

+6
objective-c macos diskarbitration
source share
2 answers

You will need the Disk Arbitration API, namely DARegisterDiskUnmountApprovalCallback.

You can create a DADiskRef through the functions available in DADisk.h

When the callback is called, you can decide whether you want to lock the unmount or not. For a far-fetched example:

 DADissenterRef myUnmountApprovalCallback(DADiskRef disk, void *context) { DADissenterRef result = NULL; // NULL means approval if (stillWorking) { // This is released by the caller, according to the docs result = DADissenterCreate(kCFAllocatorDefault, kDAReturnBusy, CFSTR("<Your App> is busy writing to this device. Please cancel the operation first."); } return result; } 

As noted in the comments, this does not stop anyone from simply pulling out the plug, but it will give you a notice of obvious outages.

+10
source share

You are looking for the Disk Arbitration (or DiskArb) APIs.

0
source share

All Articles