Hello, I am programming a CLI tool to partition USB disks. I am calling diskutil to do the work, but I am hitting issues with permissions, it seems.
Here is a trial run of the same command running diskutil directly on the terminal vs running from my code:
Calling diskutil directly (works as expected)
% /usr/sbin/diskutil partitionDisk /dev/disk2 MBR Free\ Space gap 2048S fat32 f-fix 100353S Free\ Space tail 0
Started partitioning on disk2
Unmounting disk
Creating the partition map
Waiting for partitions to activate
Formatting disk2s1 as MS-DOS (FAT32) with name f-fix
512 bytes per physical sector
/dev/rdisk2s1: 98784 sectors in 98784 FAT32 clusters (512 bytes/cluster)
bps=512 spc=1 res=32 nft=2 mid=0xf8 spt=32 hds=16 hid=2079 drv=0x80 bsec=100360 bspf=772 rdcl=2 infs=1 bkbs=6
Mounting disk
Finished partitioning on disk2
/dev/disk2 (disk image):
#: TYPE NAME SIZE IDENTIFIER
0: FDisk_partition_scheme +104.9 MB disk2
1: DOS_FAT_32 F-FIX 51.4 MB disk2s1
Calling diskutil programmatically (error -69877)
% sudo ./f-fix
DEBUG: /usr/sbin/diskutil partitionDisk /dev/disk2 MBR Free Space gap 2048S fat32 f-fix 100353S Free Space tail 0
Started partitioning on disk2
Unmounting disk
Error: -69877: Couldn't open device
(Is a disk in use by a storage system such as AppleRAID, CoreStorage, or APFS?)
Failed to fix drive `/dev/disk2'
Source Code
The relevant code from my program is this:
char *args[16]; int n = 0;
args[n++] = "/usr/sbin/diskutil";
args[n++] = "partitionDisk";
args[n++] = (char *)disk;
args[n++] = (char *)scheme;
(...)
args[n++] = NULL;
char **parent_env = *_NSGetEnviron();
if (posix_spawnp(&pid, args[0], NULL, NULL, args, parent_env) != 0)
return 1;
if (waitpid(pid, &status, 0) < 0)
return 1;
return 0;
Question
Are there any system protections against running it like so? What could I be missing? Is this a Disk Arbitration issue?