问题
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?
回答1:
utime(path, NULL);
If you have write perms, then that will give you ROFS or -- if permitted -- simply update the mtime on the directory, which is basically harmless.
回答2:
You could also popen
the command mount
and examine the output looking for your file system and seeing if it held the text " (ro,"
.
But again, that's not necessarily portable.
My option would be to not worry about whether the file system was mounted read only at all. Just try and create your file and, if it fails, tell the user what the error was. And, of course, give them the option of saving it somewhere else.
You really have to do that sort of thing anyway since, in any scenario where there's even a small gap between testing and doing, you may find the situation changes (probably not to the extent of making an entire file system read only but, who knows, maybe there is (or will be in the future) a file system that allows this).
来源:https://stackoverflow.com/questions/4894743/best-posix-way-to-determine-if-a-filesystem-is-mounted-read-only