linux获取块设备挂载信息
1、函数介绍
头文件#include<stdio.h>和#include<mntent.h>
(1)setmntent:打开文件系统描述文件的文件名,并且返回可以被使用的文件指针getmntent().
其函数原型为:
FILE * setmntent(const char * filename ,const char * type );
参数:filename 要打开的文件名字
type 表示打开文件的方式(r:只读 w:只写 r+:读写)等。
返回值:函数成功返回指向打开文件的文件指针FILE;失败返回NULL。
(2)getmntent:函数读取文件系统的下一行来自文件流的描述文件并返回指向结构的指针(即循环读取文件)
其函数原型:
struct mntent * getmntent(FILE * fp );
参数:fp setmntent函数中返回的文件指针,即将要进行读写的文件指针。
返回值:struct mntent 结构体,后面将会详细介绍该结构体的中变量和对应的作用。
(3)endmntent:关闭流和与其相关联的文件系统描述文件。
其函数原型:
int endmntent(FILE * fp );
参数:fp 函数setmntent打开的文件指针
返回值:该函数总是返回1.
2、应用举例
int ds_get_mount_info(char *in_devname, char *in_mountpoint, char *devname, char *mountpoint, char *fstype, int *is_readonly)
{
FILE *fd;
struct mntent *pent = NULL;
if((in_devname == NULL)||(in_mountpoint == NULL))
{
return -1;
}
fd = setmntent("/proc/mounts", "r");
if ( fd == NULL )
return -1;
while ( (pent = getmntent(fd)) != NULL )
{
// 找到一个匹配的设备名或挂载点就退出
if ((in_devname != NULL && strcmp(in_devname, pent->mnt_fsname) == 0)
||(in_mountpoint != NULL && strcmp(in_mountpoint, pent->mnt_dir) == 0))
{
break;
}
}
endmntent(fd);
if ( pent == NULL )
return -1;
if ( devname )
strcpy(devname, pent->mnt_fsname);
if ( mountpoint )
strcpy(mountpoint, pent->mnt_dir);
if ( fstype )
strcpy(fstype, pent->mnt_type);
if ( is_readonly )
{
if ( strstr(pent->mnt_opts, "rw") )
*is_readonly = 0;
else
*is_readonly = 1;
}
return 0;
}