If I have a POSIX system like Linux or Mac OS X, what's the best and most portable way to determine if a path is on a read-only filesystem? I can think of 4 ways off the top of my head:
open(2)
a file withO_WRONLY
- You would need to come up with a unique filename and also pass inO_CREAT
andO_EXCL
. If it fails and you have an errno ofEROFS
then you know it's a read-only filesystem. This would have the annoying side effect of actually creating a file you didn't care about, but you couldunlink(2)
it immediately after creating it.statvfs(3)
- One of the fields of the returnedstruct statvfs
isf_flag
, and one of the flags isST_RDONLY
for a read-only filesystem. However, the spec forstatvfs(3)
makes it clear that applications cannot depend on any of the fields containing valid information. It would seem there's a decent possibilityST_RDONLY
might not be set for a read-only filesystem.access(2)
- If you know the mount point, you can useaccess(2)
with theW_OK
flag as long as you are running as a user who would have write access to the mountpoint. Ie, either you are root or it was mounted with your UID as a mount parameter. You would get a return value of -1 and an errno ofEROFS
.Parsing
/etc/mtab
or/proc/mounts
- Doesn't seem portable. Mac OS X seems to have neither of these, for example. Even if the system did have/etc/mtab
I'm not sure the fields are consistent between OSes or if the mount options for read-only (ro
on Linux) are portable.
Are there other ways I'm missing? If you needed to know if a filesystem was mounted read-only, how would you do it?