挂载一个内存磁盘 mount ramfs

创建日期: 2023-05-19 18:39 | 作者: 风波 | 浏览次数: 19 | 分类: OS

方法一:使用 shell 挂载 tempfs 类型的内存磁盘

来源:https://fluffyc3rb3rus.medium.com/how-to-mount-linux-folders-into-ram-using-tmpfs-243c52ae20a2

mount -t tmpfs -o size=[desiredSize] tmpfs [folderPath]

方法二:(不推荐)使用 shell 挂载 ramfs 类型的内存磁盘

来源:https://stackoverflow.com/questions/12619686/create-a-ramdisk-in-c-on-linux

mkdir /mnt/ram
mount -t ramfs -o size=20m ramfs /mnt/ram

注意⚠️:ramfs 文件类型已经被 tempfs 替代了。

ramfs has been replaced by tmpfs as the old ramfs did not handle well when the system run out of memory. tmpfs allows the filesystem to grow dynamically when it needs more space until it hits the pre-set maximum value it has been allocated; after that it will use swap space if it is available.

方法三:使用 C语言挂载 tempfs 内存磁盘

来源:https://gist.github.com/gcmurphy/c4c5222075d8e501d7d1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mount.h>

char *
ramdisk(const char *ns, const char *sz)
{
    int rc;
    char *mountpoint = NULL, *options = NULL;
    char path[PATH_MAX];

    memset(path, 0, sizeof(path));

    const char *tmpdir = getenv("TMPDIR");
    if (! tmpdir){
        tmpdir = "/tmp/";
    }

    snprintf(path, sizeof(path)-1, "%s%s_XXXXXX", tmpdir, ns);

    mountpoint = mkdtemp(path);
    if (!mountpoint){
        return NULL;
    }

    asprintf(&options, "size=%s,uid=0,gid=0,mode=700", sz);
    rc = mount("tmpfs", mountpoint, "tmpfs", 0, options);
    free(options);

    if (rc != 0){
        perror("tmpfs creation failed");
        rmdir(mountpoint);
        return NULL;
    }
    return strdup(mountpoint);
}

#ifdef TESTING
int 
main()
{
    char *tmpfs = ramdisk("ramdisk", "1M");
    if (tmpfs != NULL){
        printf("created tmpfs here: %s\n", tmpfs);
        free(tmpfs);
    }
    return 0;
}
#endif
19 浏览
15 爬虫
0 评论