Skip to content

Instantly share code, notes, and snippets.

@talhaHavadar
Last active September 14, 2020 06:54
Show Gist options
  • Save talhaHavadar/91c530c4726dcf71666bea118420717f to your computer and use it in GitHub Desktop.
Save talhaHavadar/91c530c4726dcf71666bea118420717f to your computer and use it in GitHub Desktop.
Basic Linux Char Device Example #chardevice #linux #kernel #driver
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
MODULE_DESCRIPTION("");
MODULE_AUTHOR("Talha Can Havadar <[email protected]>");
MODULE_LICENSE("GPL");
typedef struct
{
dev_t devno;
struct cdev cdev;
struct class class;
struct file_operations fops;
} ExampleDriverStc;
static int example_open(struct inode *, struct file *);
static ExampleDriverStc exampleDriver = {
.fops = {
.owner = THIS_MODULE,
.llseek = NULL,
.read = NULL,
.write = NULL,
.unlocked_ioctl = NULL,
.open = example_open,
.flush = NULL,
.release = NULL,
},
.class = {
.owner = THIS_MODULE,
.name = "chardev-ex",
}
};
static int example_open(struct inode* inode, struct file* filp)
{
ExampleDriverStc* pDriver;
pDriver = container_of(inode->i_cdev, ExampleDriverStc, cdev);
filp->private_data = pDriver;
return 0;
}
static int __init example_init(void)
{
printk(KERN_INFO "Hello from the char device example.\n");
if (alloc_chrdev_region(&exampleDriver.devno, 0, 1, "chardev-ex") < 0)
{
printk(KERN_INFO "chardev-ex: not able to allocate char device");
return -1;
}
// Create sysfs class
if (class_register(&exampleDriver.class) < 0)
{
printk(KERN_INFO "chardev-ex: not able to register sysfs class.\n");
unregister_chrdev_region(exampleDriver.devno, 1);
return -1;
}
cdev_init(&exampleDriver.cdev, &exampleDriver.fops);
exampleDriver.cdev.owner = THIS_MODULE;
cdev_add(&exampleDriver.cdev, exampleDriver.devno, 1);
device_create(&exampleDriver.class, NULL, exampleDriver.devno, NULL, "chardev-ex-%d", 0);
return 0;
}
static void __exit example_exit(void)
{
printk(KERN_INFO "Bye from the char device example.\n");
device_destroy(&exampleDriver.class, exampleDriver.devno);
cdev_del(&exampleDriver.cdev);
class_unregister(&exampleDriver.class);
unregister_chrdev_region(exampleDriver.devno, 1);
}
module_init(example_init);
module_exit(example_exit);
obj-m += chardev-ex.o
CROSS_COMPILE=
LINUX_DIR=/lib/modules/$(shell uname -r)/build
PWD=$(shell pwd)
all:
make -C $(LINUX_DIR) M=$(PWD) modules
clean:
make -C $(LINUX_DIR) M=$(PWD) clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment