一个运行几十天甚至几个月的Linux系统中,往往运行着很多很多的监视软件,用来监视系统的状态。
对于Linux系统Mount情报的获取,网上很多帖子都有说明,在此不在多赘述。
关于Linux系统管理Mount信息的两个文件“/etc/mtab”和“/etc/fstab”,其中的每一行数据都是Mount情报。
我们可以通过读取mtab文件的中的情报,得到当前已经Mount的所有分区,通过如下函数读取:
【概要说明】
#include <stdio.h>
#include <mntent.h>
FILE *setmntent(const char *filename, const char *type);
struct mntent *getmntent(FILE *stream);
int addmntent(FILE *stream, const struct mntent *mnt);
int endmntent(FILE *streamp);
char *hasmntopt(const struct mntent *mnt, const char *opt);
/* GNU extension */
#include <mntent.h>
struct mntent *getmntent_r(FILE *streamp, struct mntent *mntbuf,
char *buf, int buflen);
【使用getmntent_r代码片段】
#include <stdio.h>
#include <string.h>
#include <mntent.h>
int main(void) {
FILE* mtab;
struct mntent mnt;
char strings[1024];
memset(&mnt,0x00,sizeof(mnt));
memset(&strings[0],0x00,sizeof(strings));
mtab = setmntent("/etc/mtab", "r");
while ((NULL != getmntent_r(mtab, &mnt, strings, sizeof(strings))))
{
if (strcmp(mnt.mnt_dir,""))
{
if(!strcmp(mnt.mnt_fsname,"/dev/sda1"))
{
printf(" sda1 Mount OK \r\n");
}
printf(" mnt_fsname [%s],mnt_dir [%s],mnt_type [%s],mnt_opts [%s], \
mnt_freq [%d],mnt_passno [%d].. \r\n", \
mnt.mnt_fsname,mnt.mnt_dir,mnt.mnt_type, \
mnt.mnt_opts,mnt.mnt_freq,mnt.mnt_passno);
}
}
(void)endmntent(mtab);
return 0;
}
【使用getmntent代码片段】
#include <stdio.h>
#include <string.h>
#include <mntent.h>
int main(void) {
FILE* mtab;
struct mntent *mnt_p;
mtab = setmntent("/etc/mtab", "r");
while ((mnt_p = getmntent(mtab)) != NULL)
{
if (strcmp(mnt_p->mnt_dir,""))
{
if(!strcmp(mnt_p->mnt_fsname,"/dev/sda1"))
{
printf(" sda2 Mount OK \r\n");
}
printf(" mnt_fsname [%s],mnt_dir [%s],mnt_type [%s],mnt_opts [%s], \
mnt_freq [%d],mnt_passno [%d].. \r\n", \
mnt_p->mnt_fsname,mnt_p->mnt_dir,mnt_p->mnt_type, \
mnt_p->mnt_opts,mnt_p->mnt_freq,mnt_p->mnt_passno);
}
}
(void)endmntent(mtab);
return 0;
}
很多人不明白getmntent函数和getmntent_r函数的区别,引用一段话:
The reentrant getmntent_r() function is similar to getmntent(), but stores the struct mount in the provided *mntbuf and stores the strings pointed to by the entries in that struct in the provided array buf of size buflen.
如果多个人同时调用getmntent会有问题,此时你需要用getmntent_r函数。
大家如果有更明白的,可以留言,我会修改补充。