在内核中创建一个简单的只写过程条目 #包括 #包括 #包括 #包括 #包括 #包括 char*msg; ssize\u t write\u proc(结构文件*filp,常量字符*buf,大小计数,loff\u t*offp) { 从用户处复制(消息、buf、计数); printk(内核信息“%s”,msg); 返回计数; } 结构文件操作过程fops={ 写入:写入进程 }; int proc_init(无效){ proc_create(“write”、0、NULL和proc_fops); 返回0; } 作废程序清理(作废){ 删除进程条目(“写入”,空); } 模块许可证(“GPL”); 模块初始化(过程初始化); 模块退出(程序清理);

在内核中创建一个简单的只写过程条目 #包括 #包括 #包括 #包括 #包括 #包括 char*msg; ssize\u t write\u proc(结构文件*filp,常量字符*buf,大小计数,loff\u t*offp) { 从用户处复制(消息、buf、计数); printk(内核信息“%s”,msg); 返回计数; } 结构文件操作过程fops={ 写入:写入进程 }; int proc_init(无效){ proc_create(“write”、0、NULL和proc_fops); 返回0; } 作废程序清理(作废){ 删除进程条目(“写入”,空); } 模块许可证(“GPL”); 模块初始化(过程初始化); 模块退出(程序清理);,c,linux,linux-kernel,linux-device-driver,procfs,C,Linux,Linux Kernel,Linux Device Driver,Procfs,当我使用命令echo'hello'>/proc/write时,终端上没有显示任何内容。你能帮我找出代码中的错误吗?我在上面写的字符串应该出现在终端上 例如: $echo'hello'>/proc/write 您好以下是对代码的一些简单修改: #include <linux/module.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include<linux/sched.h> #i

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

例如:

$echo'hello'>/proc/write


您好

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

#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);
#定义消息大小(512)
静态字符*msg;

#定义我们的最小值(a,b)(a)您没有初始化
msg
,但正在将数据复制到其中。如果您幸运的话,这将崩溃。
我在上面写的字符串应该显示在终端上。
-不,
printk
不会在终端上输出。它会写入内核日志,您可以通过
dmesg
看到。签入/var/log/messages。它会添加
msg[count]可能是个好主意=0;
在第二次
从\u用户复制\u之后
或者您可以看到以前写入的文本片段。1.无需从\u用户写入副本两次2.没有错误检查,这特别意味着printk公开了内核内存,原则上可能会运行到未映射的页面并崩溃3.缓冲区不一定为null t如果复制,则终止4.ENOMEM应为-ENOMEM。错误为否定。应使用_user注释*buf arg。最重要的是,尽管这显然是一项作业,OP对C编程语言和类unix系统的熟悉程度不足以完成任务。应建议他们向同学寻求帮助。@empLoyeofthemonth:没有两次调用,但是在内核中,
min
宏不能使用静态定义的值。因此,我选择使用if语句,而不是实现另一个。感谢您指出了其他问题,我会纠正这些问题。我的意思是,调用被编写两次,这使得函数在泛型方面更长你可以只要(count>MSG_SIZE-1)count=MSG_SIZE-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);
}