确定文件系统是否安装的最佳POSIX方法是只读的 [英] Best POSIX way to determine if a filesystem is mounted read only
问题描述
$
O_WRONLY
的文件 - 您需要创建一个唯一的文件名并传入 O_CREAT
和 O_EXCL
。如果失败,并且你有一个 EROFS
的errno,那么你知道这是一个只读的文件系统。这会产生实际上创建一个你不关心的文件的烦人的副作用,但是你可以在创建它之后马上 unlink(2)
。 statvfs(3)
- 返回的 struct statvfs $ c对于只读文件系统,$ c>是
f_flag
,其中一个标志是 ST_RDONLY
。但是, statvfs(3)
的规范清楚地表明,应用程序不能依赖任何包含有效信息的字段。看起来像 ST_RDONLY
可能没有为只读文件系统设置。
access(2)
- 如果知道挂载点,可以使用 access(2)
和 W_OK
标记,只要您以具有写入访问权限的用户身份运行挂载点即可。也就是说,你是root用户,或者是以你的UID作为挂载参数安装的。你会得到一个-1的返回值和一个errno EROFS
。 解析 / etc / mtab
或 / proc / mounts
- 似乎不便携。例如,Mac OS X似乎没有这些。即使系统确实有 / etc / mtab
我不确定这些字段在操作系统之间是否一致,或者是只读的挂载选项(
有没有其他的方法,我错过了?如果您需要知道文件系统是否以只读方式挂载,那么您将如何执行它?
utime(path,NULL);如果你有写perms,那么这将给你ROFS或 - 如果允许的话 - 只需更新目录上的mtime,基本上是无害的。
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 with O_WRONLY
- You would need to come up with a unique filename and also pass in O_CREAT
and O_EXCL
. If it fails and you have an errno of EROFS
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 could unlink(2)
it immediately after creating it.
statvfs(3)
- One of the fields of the returned struct statvfs
is f_flag
, and one of the flags is ST_RDONLY
for a read-only filesystem. However, the spec for statvfs(3)
makes it clear that applications cannot depend on any of the fields containing valid information. It would seem there's a decent possibility ST_RDONLY
might not be set for a read-only filesystem.
access(2)
- If you know the mount point, you can use access(2)
with the W_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 of EROFS
.
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?
解决方案 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.
这篇关于确定文件系统是否安装的最佳POSIX方法是只读的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!