防止移除繁忙的内核模块

Prevent removal of busy kernel module

我有一个简单的内核模块,它创建了一个字符设备但什么也不做。

我写了这个用户-space测试字符设备的程序。

int main()
{
    int fd;

    fd = open("/dev/ebbchar", O_RDWR);
    if (fd < 0)
        err(1, "open");

    sleep(10);

    ret = close(fd);
    if (ret < 0)
        err(1, "close");
}

程序在 10 秒后退出。

但如果我同时使用 rmmod 或 modprobe 删除模块,则 10 秒后程序会出现段错误或挂起,并且出现内核错误。

我怎样才能导致 rmmod 失败,或者是否有安全删除模块的方法?

我的模块能否在其 __exit 函数中关闭文件描述符?

我假设崩溃是由 close() 函数引起的,该函数在字符文件操作中间接调用 release 回调,而 release 函数不再存在,因为模块已删除。

可以找到内核模块的源代码 here(搜索 清单 2)。

IIRC 您需要在文件操作结构中设置 .owner = THIS_MODULE 以便正确处理模块的引用计数。