Skip to content

Instantly share code, notes, and snippets.

@JonnyJD
Last active December 20, 2015 09:09
Show Gist options
  • Save JonnyJD/6105296 to your computer and use it in GitHub Desktop.
Save JonnyJD/6105296 to your computer and use it in GitHub Desktop.
Preliminary tests to implement drutil's optical disc drive numbering in C
#include <IOKit/IOKitLib.h>
#include <IOKit/IOBSD.h>
#include <IOKit/storage/IOCDMedia.h>
#include <IOKit/storage/IOCDBlockStorageDevice.h>
#include <CoreFoundation/CoreFoundation.h>
#define MAXPATHLEN 1024
static void find_cd_media(io_iterator_t *mediaIterator)
{
mach_port_t masterPort;
CFMutableDictionaryRef classesToMatch;
IOMasterPort(MACH_PORT_NULL, &masterPort);
classesToMatch = IOServiceMatching(kIOCDMediaClass);
IOServiceGetMatchingServices(masterPort, classesToMatch, mediaIterator);
}
static void find_cd_block_devices(io_iterator_t *deviceIterator)
{
mach_port_t masterPort;
CFMutableDictionaryRef classesToMatch;
IOMasterPort(MACH_PORT_NULL, &masterPort);
classesToMatch = IOServiceMatching(kIOCDBlockStorageDeviceClass);
IOServiceGetMatchingServices(masterPort, classesToMatch, deviceIterator);
}
static int get_device_file_path(io_object_t nextMedia, char * deviceFilePath)
{
CFTypeRef deviceFilePathAsCFString;
*deviceFilePath = '\0';
deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(nextMedia,
CFSTR(kIOBSDNameKey), kCFAllocatorDefault, 0);
if (deviceFilePathAsCFString)
{
if (CFStringGetCString(deviceFilePathAsCFString, deviceFilePath,
MAXPATHLEN, kCFStringEncodingASCII)) {
return 1;
}
CFRelease(deviceFilePathAsCFString);
}
return 0;
}
static int print_object_class(io_object_t object)
{
io_name_t className;
IOObjectGetClass(object, className);
fprintf(stderr, "\tclass name: %s\n", className);
}
static void print_info_for_objects(io_iterator_t objectIterator)
{
io_object_t nextObject;
char device_name[MAXPATHLEN+1] = "\0";
int index = 0;
while ((nextObject = IOIteratorNext(objectIterator))) {
fprintf(stderr, "drive %d:\n", ++index);
if (get_device_file_path(nextObject, device_name))
fprintf(stderr, "\tdevice name: %s\n", device_name);
print_object_class(nextObject);
IOObjectRelease(nextObject);
}
}
int main() {
io_iterator_t objectIterator;
fprintf(stderr, "detected media:\n");
find_cd_media(&objectIterator);
print_info_for_objects(objectIterator);
fprintf(stderr, "detected CD block devices:\n");
find_cd_block_devices(&objectIterator);
print_info_for_objects(objectIterator);
}
disc_drive_numbers: disc_drive_numbers.c
${CC} $^ -framework CoreFoundation -framework IOKit -o $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment