62 lines
1.4 KiB
C
62 lines
1.4 KiB
C
#ifndef __KERNEL__
|
|
#define __KERNEL__
|
|
#endif
|
|
#ifndef MODULE
|
|
#define MODULE
|
|
#endif
|
|
#include <linux/kernel.h>
|
|
#include <linux/module.h>
|
|
#include <linux/fs.h>
|
|
#include <linux/uaccess.h>
|
|
|
|
#define SUCCESS 0
|
|
#define DEVICE_NAME "kueng_char_dev"
|
|
#define BUF_LEN 50
|
|
|
|
static int Device_Open = 0;
|
|
static char Message[BUF_LEN];
|
|
static int Major;
|
|
|
|
static int mydev_open(struct inode *inode, struct file *file) {
|
|
if (Device_Open) return -EBUSY;
|
|
Device_Open = 1;
|
|
return 0;
|
|
}
|
|
|
|
static int mydev_release(struct inode *inode, struct file *file) {
|
|
Device_Open = 0;
|
|
return 0;
|
|
}
|
|
|
|
static ssize_t mydev_read(struct file *file, char *buffer, size_t length, loff_t *f_pos) {
|
|
return copy_to_user(buffer, Message, length);
|
|
}
|
|
|
|
static ssize_t mydev_write(struct file *file, const char *buffer, size_t length, loff_t *f_pos) {
|
|
int len = BUF_LEN < length ? BUF_LEN : length;
|
|
return copy_from_user(Message, buffer, len);
|
|
}
|
|
|
|
static struct file_operations fops = {
|
|
.open = mydev_open,
|
|
.release = mydev_release,
|
|
.read = mydev_read,
|
|
.write = mydev_write,
|
|
};
|
|
|
|
int init_module(void) {
|
|
Major = register_chrdev(0, DEVICE_NAME, &fops);
|
|
if (Major < 0) {
|
|
printk("Register char device failed\n");
|
|
return Major;
|
|
}
|
|
printk("Registered with major %d\n", Major);
|
|
return 0;
|
|
}
|
|
|
|
void cleanup_module(void) {
|
|
unregister_chrdev(Major, DEVICE_NAME);
|
|
}
|
|
|
|
MODULE_LICENSE("GPL");
|
|
MODULE_AUTHOR("KUENG"); |