Lua挂载文件系统

我想在Linux上使用Lua挂载文件系统, 但我在lua 5.4手册LuaFileSystem库中没有找到任何能力。是否有一些方法在Lua或使用现有库中挂载文件系统?

点赞
用户7020163
用户7020163

像大多数依赖平台的系统调用一样,Lua本身不提供这种映射。因此,你需要一些能够完成这个工作的C API模块。看起来https://github.com/justincormack/ljsyscall是通用的,但它的重点是LuaJIT,而https://luaposix.github.io/luaposix/ 不提供 mount

最近我也有类似的需求,于是我自己写了一个C模块:

static int l_mount(lua_State* L)
{
    int res = 0;
    // TODO add more checks on args!
    const char *source = luaL_checkstring(L, 1);
    const char *target = luaL_checkstring(L, 2);
    const char *type   = luaL_checkstring(L, 3);
    lua_Integer flags  = luaL_checkinteger(L, 4);
    const char *data   = luaL_checkstring(L, 5);

    res = mount(source, target, type, flags, data);
    if ( res != 0)
    {
        int err = errno;
        lua_pushnil(L);
        lua_pushfstring(L, "mount failed: errno[%s]", strerror(err));
        return 2;
    }
    else
    {
        lua_pushfstring(L, "ok");
        return 1;
    }
}

#define register_constant(s)\
    lua_pushinteger(L, s);\
    lua_setfield(L, -2, #s);

// Module functions
static const luaL_Reg R[] =
{
    { "mount", l_mount },
    { NULL, NULL }
};

int luaopen_sysutils(lua_State* L)
{
    luaL_newlib(L, R);

    // do more mount defines mapping, maybe in some table.
    register_constant(MS_RDONLY);
    //...

    return 1;
}

将其编译为C Lua模块,并且不要忘记你需要 CAP_SYS_ADMIN 来调用 mount 系统调用。

2020-10-21 08:15:25