c - 使用 proc 的内核模块程序

标签 c linux linux-kernel

我制作了以下内核模块以在/proc 目录中创建进程“hello_proc”:

#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>

static int hello_proc_show(struct seq_file *m, void *v) 
{
    seq_printf(m, "P5 : Hello proc!\n");
    return 0;
}

static int hello_proc_open(struct inode *inode, struct  file *file) 
{
    return single_open(file, hello_proc_show, NULL);
}

static const struct file_operations hello_proc_fops = {
    .owner = THIS_MODULE,
    .open = hello_proc_open,
    .read = seq_read,
    //.write = seq_write,
    .llseek = seq_lseek,
    .release = single_release,
};

static int hello_proc_init(void) 
{
    proc_create("hello_proc", 0, NULL, &hello_proc_fops);
    //printk("P5 : Process hello proc created");
    return 0;
}

static void hello_proc_exit(void) 
{
    remove_proc_entry("hello_proc", NULL);
}

MODULE_LICENSE("GPL");
module_init(hello_proc_init);
module_exit(hello_proc_exit);

我现在想写入(和读取)命令的内容,例如“ls -l/proc” 到 proc 文件“hello_proc”。

我的问题是,如何解决在将以下数据写入 proc 文件“hello_proc”时遇到的以下错误:

anubhav@anubhav-Inspiron-3421:~/Desktop/pro/p5$ sudo ls -l -t /proc | head -21 > /proc/hello_proc
bash: /proc/hello_proc: Permission denied 

anubhav@anubhav-Inspiron-3421:~/Desktop/pro/p5$ ls -l -t /proc | head -21 > sudo /proc/hello_proc
ls: cannot access /proc/4273: No such file or directory

anubhav@anubhav-Inspiron-3421:~/Desktop/pro/p5$ ls -l -t /proc | head -21 > /proc/hello_proc
bash: /proc/hello_proc: Permission denied

最佳答案

首先要解决Permission Denied Error

  1. root (su) 身份登录
  2. 运行命令

    $ ls -l -t /proc | head -21 > /proc/hello_proc
    

现在您将面临另一个问题,如下所示。

head: write error: Input/output error
head: write error

原因是您没有为 proc 文件编写写文件操作 fops。在代码中,您已经注释掉了写入操作。

关于c - 使用 proc 的内核模块程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159834/

相关文章:

linux - 如何在命令行中将 markdown 转换为 pdf

c - Linux Kernel Makefile.build 构建外部模块时的奇怪行为

linux - 正则表达式和 grep

linux - Unix 表示怀疑 - 对以下程序的执行

c - Linux 中 inet_addr_lst 内核符号的用途是什么?

c - 如何在 C LPWSTR 上进行字符串比较?

c - scanf 之后 fgets 不起作用

c - C 程序的运行时错误

c - 为什么我在 "if (fd=fopen(fileName,"r") == NULL)"中收到此警告?

linux - 如何在bash中复制字符串直到另一个字符串