【问题标题】:Creating a simple write only proc entry in kernel在内核中创建一个简单的只写 proc 条目
【发布时间】:2016-12-05 23:49:47
【问题描述】:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include<linux/sched.h>
#include <asm/uaccess.h>
#include <linux/slab.h>

char *msg;

ssize_t write_proc(struct file *filp,const char *buf,size_t count,loff_t *offp)
{
    copy_from_user(msg,buf,count);
    printk(KERN_INFO "%s",msg);

    return count;
}

struct file_operations proc_fops = {
    write: write_proc
};


int proc_init (void) {
    proc_create("write",0,NULL,&proc_fops);

    return 0;
}

void proc_cleanup(void) {
    remove_proc_entry("write",NULL);
}

MODULE_LICENSE("GPL"); 
module_init(proc_init);
module_exit(proc_cleanup);

当我使用命令 echo 'hello' &gt; /proc/write 时,终端上没有任何显示。你能帮我找出代码中的错误吗?我写在上面的字符串应该会显示在终端上。

例子:

$ echo 'hello' > /proc/write

你好

【问题讨论】:

  • 你没有初始化msg,但是你正在向它复制数据。那会崩溃……如果你幸运的话。
  • The string that I write on it should have shown up on terminal. - 不,printk 不会在终端上输出。它写入内核日志,您可以通过dmesg 看到。
  • 签入 /var/log/messages。

标签: c linux linux-kernel linux-device-driver procfs


【解决方案1】:

以下是对您的代码的一些简单修改:

#define MSG_SIZE (512)
static char *msg;

#define ourmin(a,b) (((a)<(b)) ? (a) : (b))

ssize_t write_proc(struct file *filp,const char *buf,size_t count,loff_t *offp)
{
   unsigned long actual_len = ourmin(count, MSG_SIZE-1);
   memset(msg, 0, MSG_SIZE);
   copy_from_user(msg, buf, actual_len);

   printk(KERN_DEBUG "Got: %s",msg);

   return count;
}

int proc_init (void) {
  // Allocate space for msg
  if ((msg = kmalloc(MSG_SIZE, GFP_KERNEL)) == NULL)
    return -ENOMEM;

  // Should check the output of this too
  proc_create("write",0,NULL,&proc_fops);

  return 0;
}

void proc_cleanup(void) {
    remove_proc_entry("write",NULL);
    kfree(msg);
}

我可以在内核日志中检索输出(例如dmesg)。

【讨论】:

  • 在第二个copy_from_user 之后添加msg[count] = 0; 可能是个好主意,否则您可以看到以前写入的文本片段。
  • 1.不需要写两次 copy_from_user 2. 没有错误检查,这特别意味着 printk 公开了内核内存,原则上可以遇到未映射的页面并崩溃 3. 如果复制缓冲区不一定为 null 终止 4. ENOMEM 应该是-ENOMEM。错误是消极的。 *buf arg 应使用 __user 进行注释。最重要的是,尽管很明显这是一项任务,并且 OP 对 C 编程语言和类 unix 系统的熟悉程度不足以完成任务。应该建议他们向同学寻求帮助。
  • @employeeofthemonth:没有调用两次,但在内核中,min 宏不适用于静态定义的值。因此,我没有实现另一个,而是选择使用 if 语句。感谢您指出其他问题,我会更正。
  • 我的意思是调用被编写了两次,这使得函数在生成的程序集方面更长。如果 (count > MSG_SIZE - 1) count = MSG_SIZE - 1;并完成它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多