我可以创建一个“文件”,当打开时,它实际上会给出命令的输出吗?

我可以创建一个“文件”,当打开时,它实际上会给出命令的输出吗?

我现在发现自己处于一些情况中,我希望有这样一个“文件”,它基本上在“打开”时运行一个脚本,允许我“读取”它的输出。

例如,我可能在某个项目中有一个配置文件,我想在本地使用,但由于我的机器不同,我需要在其上运行 sed 或 grep 才能使其工作。项目的配置文件仍在维护中,我希望这些更改出现在我的本地配置中。这意味着通过修改它然后保存它来做简单的事情并不理想,因为随着项目的更新,它很容易变得陈旧。我希望每次打开本地配置文件时都会进行过滤。

有什么方法可以实现这种功能吗?我知道虚拟文件系统允许你将一些非常疯狂的东西显示为“文件”,所以我觉得这并非不可能。

答案1

理论上,使用 LD_PRELOAD 与所需程序就可以实现。

编写一个库来在“打开”系统调用上添加一个包装器,并使用原始程序(比如cat)作为LD_PRELOAD=/path/to/library cat

包装库中的 overridden_​​open() 代码看起来类似于以下虚拟代码。

/* This is an illustrative code, and doesn't follow any good coding practice. */
int overridden_open (...)
{
    /* Only do this for the config file. */
    if (strcmp (filename, "/path/to/required/config/file") == 0)
    {
        /* Download a fresh copy, and if successful, overwrite the existing file. */
        if (system ("wget -O /path/to/required/config/file.tmp http://remote.file/url") == 0 && system ("<perform awk/sed/grep operations>") == 0)
        {
            system ("mv /path/to/required/config/file.tmp /path/to/required/config/file");
        }
    }
    return open (...);
}

相关内容