【发布时间】:2014-12-02 07:41:50
【问题描述】:
我使用以下代码作为参考从 Solaris 11.2 机器获取卷列表:
#include <time.h>
#include <sys/mntent.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <errno.h>
struct mntent
{
char *mnt_fsname; /* Device or server for filesystem. */
char *mnt_dir; /* Directory mounted on. */
char *mnt_type; /* Type of filesystem: ufs, nfs, etc. */
char *mnt_opts; /* Comma-separated options for fs. */
int mnt_freq; /* Dump frequency (in days). */
int mnt_passno; /* Pass number for `fsck'. */
};
char ** getVolumeList(int * size)
{
char ** volList = NULL;
int listLen = 0;
char tmp[1024];
struct mntent* vp ;
FILE *fp=fopen("/etc/mnttab", "r");
int result;
printf("in getVolumeList\n");
printf("coming here 1\n");
volList = (char **) malloc(sizeof(char*) * (*size));
printf("coming here \n");
vp = getmntent(fp);
if (vp == NULL)
printf("vp is null");
result = getmntent(fp,vp);
if(result == -1)
{
printf ("getmntent returned:%d. Hence breaking from loop\n", result);
}
/*
ignore all entries for which mount options is set to ignore
these don't show up in dk -k also although dk -a shows them
*/
if(vp->mnt_dir != NULL)
{
strcpy(tmp,vp->mnt_dir);
volList[listLen] = (char*) malloc(sizeof(char) * (strlen(tmp)+1));
strcpy(volList[listLen], tmp);
listLen++;
}
else
{
printf("\nmountp is NULL \n");
}
printf("freeing vp\n");
if (vp != NULL)
{
free(vp);
}
if (fp != NULL)
{
fclose(fp);
}
*size = listLen;
printf("returning from getVolumeList\n");
return volList;
}
但这似乎引发了以下段错误:
#0 0xfe663923 in getmntent_compat () from /lib/libc.so.1
我猜这是因为 solaris 11.2 上的 mntent.h 在头文件中没有定义 struct mntent 或以下方法签名: getmntent(); getmntent(fp,vp)
是否有任何其他等效的方法来确定安装在 Solaris 机器上的卷,或者更好的独立于操作系统的方法来确定当前安装的卷?
附:我是 C 新手。
【问题讨论】:
-
1:包含
文件以获取结构定义。 2> getmntent 只接受一个参数,你至少传递两个参数一次。编译时启用警告。 3> 不要释放mntent。 4>不要使用fopen,使用setmntent。 5> tmp 至少应为 PATH_MAX 长。 6> 使用 endmntent 停止读取文件。可能还有其他问题。 :) -
另外,你根本不需要 tmp 变量,另外,如果你使用 strdup,就不需要 malloc+strcpy。
-
或者简单地说:system("mount");
标签: c filesystems solaris mount