proc 下创建与应用交互的可读写节点

内核版本:Linux-4.14

随便写了个 proc 下节点的测试程序,可以用来与应用层交互。

也可以单独的用来做调试打印使用,例如封装个 my_printk 将信息单独存在节点内,然后可以在应用层 cat 出来查看。

 1 #include <linux/uaccess.h>
 2 #include <linux/proc_fs.h>
 3 #include <linux/module.h>
 4 #include <linux/kernel.h>
 5 #include <linux/delay.h>
 6 #include <asm/uaccess.h>
 7 #include <linux/sched.h>
 8 #include <linux/init.h>
 9 #include <asm/irq.h>
10 #include <asm/io.h>
11 
12 #define MSG_BUF_LEN     1024
13 
14 static unsigned char msg_buf[MSG_BUF_LEN] = {0};
15 static unsigned int msg_len = 0;
16 static DECLARE_WAIT_QUEUE_HEAD(proc_msg_waitq);
17 
18 static ssize_t proc_msg_read(struct file *file, char __user *user_buf,
19              size_t count, loff_t *ppos)
20 {
21     unsigned int ret = 0;
22         
23     /* 如果 msg_len 为 0,则等待数据 */
24     wait_event_interruptible(proc_msg_waitq, msg_len);
25     copy_to_user(user_buf, msg_buf, msg_len);
26     ret = msg_len;
27     msg_len = 0;
28     
29     return ret;
30 }
31 
32 static ssize_t proc_msg_write(struct file *file, const char __user *user_buf,
33              size_t count, loff_t *ppos)
34 {
35     if(copy_from_user(msg_buf, user_buf, count)) {
36         return -EFAULT;
37     }
38     msg_len = count;
39     wake_up_interruptible(&proc_msg_waitq);
40     
41     return count;
42 }
43 
44 const struct file_operations proc_msg_operations = {
45     .read =    proc_msg_read,
46     .write = proc_msg_write,
47 };
48 
49 static int proc_msg_init(void)
50 {
51     /* 在 proc 下创建了 proc_msg */
52     proc_create("proc_msg", S_IRUSR, NULL, &proc_msg_operations);
53     
54     return 0;    
55 }
56 
57 static void proc_msg_exit(void)
58 {
59     remove_proc_entry("proc_msg", NULL);
60 }
61 
62 module_init(proc_msg_init);
63 module_exit(proc_msg_exit);
64 MODULE_LICENSE("GPL");

编译脚本如下:

KERN_DIR = /home/lance/nanopi/linux-4.14/

all:
    make -C $(KERN_DIR) M=`pwd` modules
    rm -rf *.o *.bak *.order *.mod.c *.symvers

clean:
    make -C $(KERN_DIR) M=`pwd` modules clean

obj-m    += proc_msg.o

安装模块测试:

/ # insmod proc_msg.ko 
/ # echo hello > /proc/proc_msg 
/ # cat /proc/proc_msg 
hello

成功输出节点内信息。

原文地址:https://www.cnblogs.com/GyForever1004/p/12044101.html