以下内容由chatgpt给出
以下是一个使用procfs接口创建设备节点的示例代码:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "my_device"
#define PROC_NAME "my_proc"
static int major;
static struct proc_dir_entry *proc_entry;
static int my_device_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "my_device: device opened\n");
return 0;
}
static ssize_t my_device_read(struct file *file, char __user *buf, size_t count, loff_t *pos)
{
printk(KERN_INFO "my_device: device read\n");
return 0;
}
static ssize_t my_device_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
{
printk(KERN_INFO "my_device: device write\n");
return count;
}
static const struct file_operations my_device_fops = {
.owner = THIS_MODULE,
.open = my_device_open,
.read = my_device_read,
.write = my_device_write,
};
static int my_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "Hello, world!\n");
return 0;
}
static int my_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, my_proc_show, NULL);
}
static const struct proc_ops my_proc_fops = {
.owner = THIS_MODULE,
.open = my_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init my_module_init(void)
{
major = register_chrdev(0, DEVICE_NAME, &my_device_fops);
if (major < 0) {
printk(KERN_ALERT "Failed to register character device\n");
return major;
}
proc_entry = proc_create(PROC_NAME, 0, NULL, &my_proc_fops);
if (!proc_entry) {
printk(KERN_ALERT "Failed to create proc entry\n");
unregister_chrdev(major, DEVICE_NAME);
return -ENOMEM;
}
printk(KERN_INFO "my_module loaded\n");
return 0;
}
static void __exit my_module_exit(void)
{
proc_remove(proc_entry);
unregister_chrdev(major, DEVICE_NAME);
printk(KERN_INFO "my_module unloaded\n");
}
module_init(my_module_init);
module_exit(my_module_exit);
MODULE_LICENSE("GPL");
在这个示例中,我们使用了procfs接口创建了一个名为my_proc
的文件,它的内容是Hello, world!
。同时,我们还创建了一个名为my_device
的字符设备节点,它的操作函数分别是my_device_open
、my_device_read
和my_device_write
。
procfs是Linux内核提供的一种伪文件系统,它允许用户空间程序通过文件I/O的方式访问内核数据结构。procfs的根目录是/proc
,它包含了一系列以数字命名的目录,每个目录对应一个进程。在这些目录下,又有一些以文件名命名的文件,它们对应了进程的各种信息,比如进程的命令行参数、内存映射、文件描述符等等。
除了进程信息之外,procfs还提供了一些其他的信息,比如系统信息、设备信息等等。用户空间程序可以通过procfs接口创建自己的文件,以提供自定义的信息。在内核中,可以使用proc_create
函数创建一个procfs文件,它的参数包括文件名、文件权限、父目录和文件操作函数等等。在文件操作函数中,可以实现读取和写入文件的逻辑。