In the code given below:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/disk.h>
int main(int argc, char **argv)
{
int fd = open("/dev/disk0", O_RDONLY, 0);
...
}
fd has -1 for physical hard drives but it works fine for a USB/flash drive. Why is this happening?
This is almost certainly a permissions issue. Giving ordinary users any access to raw disks is a security hole (the user could circumvent all file permissions and read anything they want on the disk), so no OS gives raw disk access to normal users.
In the example below,
disk0is my internal hard drive anddisk3is a USB flash drive. In OS X, even “administrators” aren’t part of theoperatorgroup that would allow raw disk access to fixed hard drives.pip$ ls -ltr /dev/disk*
brw-r----- 1 root operator 14, 3 Dec 12 10:14 /dev/disk0s3
brw-r----- 1 root operator 14, 2 Dec 12 10:14 /dev/disk0s2
brw-r----- 1 root operator 14, 1 Dec 12 10:14 /dev/disk0s1
brw-r----- 1 root operator 14, 0 Dec 12 10:14 /dev/disk0
br--r----- 1 root operator 14, 4 Dec 14 15:15 /dev/disk1
brw-r----- 1 root operator 14, 7 Dec 14 15:15 /dev/disk2s2
br--r----- 1 root operator 14, 6 Dec 14 15:15 /dev/disk2s1
brw-r----- 1 root operator 14, 5 Dec 14 15:15 /dev/disk2
brw-r----- 1 pip operator 14, 9 Dec 14 15:18 /dev/disk3s1
brw-r----- 1 pip operator 14, 8 Dec 14 15:18 /dev/disk3
If your app really needs raw disk access you’ll either need to run it as root with
sudo, add yourself to theoperatorgroup, or use the OS X APIs for privilege escalation.