Linux mount() 编程

UNIX/Linux操作系统将所有文件管理成一棵倒过来的树,根是目录'\'。文件可以来自不同的设备,当一个新的设备要挂到这棵树上时,我们使用mount命令;反之我们使用umount命令。

在Linux shell中,我们可以这样做:

# mount -t ext3 /dev/vdd /opt3

# ls /opt3
dir_a  dir_b  lost+found

# umount /opt3

# ls /opt3
#

我们也可以用C语言中API mount()来实现上述功能:

# cat mount-exampe.c

#include <stdlib.h>    //exit(), system()
#include <stdio.h>     //printf()
#include <sys/mount.h> //mount()
#include <dirent.h>    //struct dirent,DIR,opendir(),readdir()
#include <string.h>    //strcmp()

void die(char *s)
{
    perror(s);
    exit(1);
}

#define TDIR "/opt4"

int main()
{
    char cmd[64];

    sprintf(cmd, "mkdir %s", TDIR);
    if (system(cmd) != 0)
    {
        die("cmd");
    }

    if (mount("/dev/vdd", TDIR, "ext3", 0, NULL) != 0)
    {
        die("mount()");
    }

    struct dirent * entry;
    DIR * dir;

    dir = opendir(TDIR);
    if (!dir)
    {
        die("opendir()");
    }

    while ((entry = readdir(dir)))
    {
        if (strcmp(entry->d_name, ".") == 0)
            continue;
        if (strcmp(entry->d_name, "..") == 0)
            continue;
        printf("%s ", entry->d_name);
    }

    printf("\n");
    closedir(dir);
    umount(TDIR);

    sprintf(cmd, "rm -rf %s", TDIR);
    if (system(cmd) != 0)
    {
        die("cmd");
    }
}
# gcc mount-example.c -o mount-example && ./mount-example
dir_a dir_b lost+found
#
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,206评论 2 33
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,514评论 9 467
  • 1.Linux下如何用命令查看实时日志(完整命令) tail -f 路径.log查看前多少行 tai-200f 路...
    qianyewhy阅读 2,316评论 0 11
  • Linux系统一般有4个主要部分: 内核、shell、文件系统和应用程序。内核、shell和文件系统一起形成了基本...
    偷风筝的人_阅读 3,272评论 1 17
  • 《读书笔记》 原文: 一把坚实的大锁挂在大门上,一根铁杆费了九牛二虎之力,还是无法将它撬开。钥匙来了,他瘦小的身子...
    临淄茂业DDM黄红阅读 268评论 0 0