Creating Linux Filesystems Reliably With flock

A coworker brought this up, and it’s worth noting:

what's wrong with this?

    # parted -s /dev/sda mkpart primary ext2 1M 8M
    # mke2fs /dev/sda1

Unfortunately, this will occasionally fail with this error from mk2fs:

    The file /dev/sda1 does not exist and no size was specified.

This is due to a race condition in the udevd and mke2fs. Since /dev/sda has just been changed, udevd watches for a “close after open for writing” signal from inotify, and then does a BLKRRPART ioctl on /dev/sda. If mk2efs tries to write during this time, /dev/sda1 may briefly not exist.

But flock will prevent the BLKRRPART from being issued, so this will reliably create a partition:

flock -s /dev/sda -c "parted -s /dev/sda mkpart primary ext2 1M 8M && mke2fs /dev/sda1"