gpt4 book ai didi

在内核中创建一个简单的只写 proc 条目

转载 作者:太空狗 更新时间:2023-10-29 11:50:14 27 4
gpt4 key购买 nike

#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' >/proc/write 终端上没有任何显示。你能帮我找出代码中的错误吗?我在上面写的字符串应该会出现在终端上。

示例:

$ echo '你好' >/proc/write

你好

最佳答案

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

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

关于在内核中创建一个简单的只写 proc 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com