Re: Detecting ro Filesystem
On Sun, May 04, 2003 at 07:04:57AM +0200, Bernd Eckenfels wrote:
> On Sat, May 03, 2003 at 09:44:45PM -0500, John Hasler wrote:
> > What is a reliable, robust, and simple way to detect that a file is on a ro
> > filesystem?
>
> No because there are a lot of influences. Cause you can try to parse the
> mountpoint, but that will not catch other restrictions like ACLs, Labels and
> so on. The most easiest thing is to open the file for write, and perhaps
> even try to write to it. Be aware that it might be in append only or copy on
> write mode.
As Bernd has pointed out, there are many reasons why even root might
not be able to write to a file (for example, the file might have a
immutable or append-only attribute set on it --- which some
filesystems such as ext2/3 support).
However, if we are to take you at your word that the only thing which
you are interested in is whether or not a filesystem is mounted
read-only, the following excerpt (which requires linking against
liblkid and libext2fs libraries) should do the trick. I haven't
tested this or even compiled it, but it should give you the the
idea....
#include <ext2fs/ext2fs.h>
#include <blkid/blkid.h>
/*
* Returns a non-negative value file is on a filesystem mounted read-only,
* zero if not, and a negative value if there was an error while attempting
* to make this determination.
*/
int is_on_ro_filesystem(const char *file)
{
struct stat st;
const char *devname;
if (stat(file, &st) < 0)
return -1;
devname = blkid_devno_to_devname(st.st_dev);
if (!devname)
return -1;
if (ext2fs_check_if_mounted(devname, &mount_flags)) {
free(devname);
return -1;
}
free(devname);
return (mount_flags & EXT2_MF_READONLY);
}
Note: despite using libraries from e2fsprogs, this will work for any
filesystem, so long as /proc/mounts (or /proc is not mounted,
/etc/mtab) is accurate. The blkid library is present on e2fsprogs
1.33 and newer (available in unstable).
- Ted
Reply to: