99 lines
2.5 KiB
C
99 lines
2.5 KiB
C
/*
|
|
* procfs2.c - 在/proc中创建一个 "文件"
|
|
*/
|
|
|
|
#include <linux/kernel.h>
|
|
#include <linux/module.h>
|
|
#include <linux/proc_fs.h> /* 使用 procfs 时的必要模块 */
|
|
#include <linux/uaccess.h> /* 引入 copy_from_user */
|
|
#include <linux/version.h>
|
|
|
|
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)
|
|
#define HAVE_PROC_OPS
|
|
#endif
|
|
|
|
#define PROCFS_MAX_SIZE 1024
|
|
#define PROCFS_NAME "buffer1k"
|
|
|
|
/* 此结构保存有关 /proc 文件的信息 */
|
|
static struct proc_dir_entry *our_proc_file;
|
|
|
|
/* 用于存储此模块字符的缓冲区 */
|
|
static char procfs_buffer[PROCFS_MAX_SIZE];
|
|
|
|
/* 缓冲区的大小 */
|
|
static unsigned long procfs_buffer_size = 0;
|
|
|
|
/* 在读取 /proc 文件时调用该函数 */
|
|
static ssize_t procfile_read(struct file *file_pointer, char __user *buffer,
|
|
size_t buffer_length, loff_t *offset)
|
|
{
|
|
char s[13] = "HelloWorld!\n";
|
|
int len = sizeof(s);
|
|
ssize_t ret = len;
|
|
|
|
if (*offset >= len || copy_to_user(buffer, s, len)) {
|
|
pr_info("copy_to_user 执行结束 \n");
|
|
ret = 0;
|
|
} else {
|
|
pr_info("读取项目文件: %s\n", file_pointer->f_path.dentry->d_name.name);
|
|
*offset += len;
|
|
}
|
|
|
|
return ret;
|
|
}
|
|
|
|
/* 在写入 /proc 文件时调用该函数 */
|
|
static ssize_t procfile_write(struct file *file, const char __user *buff,
|
|
size_t len, loff_t *off)
|
|
{
|
|
procfs_buffer_size = len;
|
|
if (procfs_buffer_size > PROCFS_MAX_SIZE)
|
|
procfs_buffer_size = PROCFS_MAX_SIZE;
|
|
|
|
if (copy_from_user(procfs_buffer, buff, procfs_buffer_size))
|
|
return -EFAULT;
|
|
|
|
procfs_buffer[procfs_buffer_size & (PROCFS_MAX_SIZE - 1)] = '\0';
|
|
*off += procfs_buffer_size;
|
|
pr_info("写入项目文件 %s\n", procfs_buffer);
|
|
|
|
return procfs_buffer_size;
|
|
}
|
|
|
|
#ifdef HAVE_PROC_OPS
|
|
static const struct proc_ops proc_file_fops = {
|
|
.proc_read = procfile_read,
|
|
.proc_write = procfile_write,
|
|
};
|
|
#else
|
|
static const struct file_operations proc_file_fops = {
|
|
.read = procfile_read,
|
|
.write = procfile_write,
|
|
};
|
|
#endif
|
|
|
|
static int __init procfs2_init(void)
|
|
{
|
|
our_proc_file = proc_create(PROCFS_NAME, 0644, NULL, &proc_file_fops);
|
|
if (NULL == our_proc_file) {
|
|
pr_alert("错误: 无法初始化 /proc/%s\n", PROCFS_NAME);
|
|
return -ENOMEM;
|
|
}
|
|
|
|
pr_info("/proc/%s 已创建\n", PROCFS_NAME);
|
|
return 0;
|
|
}
|
|
|
|
static void __exit procfs2_exit(void)
|
|
{
|
|
proc_remove(our_proc_file);
|
|
pr_info("/proc/%s 已卸载\n", PROCFS_NAME);
|
|
}
|
|
|
|
module_init(procfs2_init);
|
|
module_exit(procfs2_exit);
|
|
|
|
MODULE_LICENSE("GPL");
|
|
|