【磁盘管理】linux获取块设备挂载信息

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;
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值