Creating a simple write only proc entry in kernel

混江龙づ霸主 提交于 2021-01-28 01:06:21

问题


#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);

When I used the command echo 'hello' > /proc/write Nothing show up on terminal . Can you help me to find mistakes in the code ? The string that I writed on it should have show up on terminal.

Example :

$ echo 'hello' > /proc/write

hello


回答1:


Here are some simple modifications on your code:

#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);
}

I could retrieve the output in the kernel log (dmesg for instance).



来源:https://stackoverflow.com/questions/40985462/creating-a-simple-write-only-proc-entry-in-kernel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!