|
这是Makefile文件
DFLAGS = -D__KERNEL__ -DMODULE -Wall -DLINUX -O2 -o
mydrv.o: mydrv.c /usr/include/linux/version.h
gcc $(DFLAGS) -c mydrv.c
clean:
rm -f *.o
这是源码
#include <linux/kernel.h>
#include <linux/module.h>
#if CONFIG_MODVERSIONS==1
#define MODVERSIONS
#include <linux/modversions.h>
#endif
#include <linux/fs.h>
#include <linux/wrapper.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "char_dev"
#define BUF_LEN 100
static int Device_Open = 0;
static char Message[BUF_LEN];
static char *Message_Ptr;
static int Major;
static int device_open(struct inode *inode, struct file *file)
{
static int counter = 0;
printk("Device: %d.%d\n", inode->i_rdev >> 8, inode->i_rdev & 0xFF);
if (Device_open)
return -EBUSY;
Device_Open++;
sprintf(Message, "If I told you once, I told you %d times - %s",
counter++, "Hello, world\n");
Message_Ptr = Message;
MOD_INC_USE_COUNT;
return SUCCESS;
}
static int device_release(struct inode *inode, struct file *file)
{
Device_Open--;
MOD_DEC_USE_COUNT;
return 0;
}
static ssize_t device_read(struct file *file,char *buffer,
size_t length, loff_t *offset)
{
int bytes_read = 0;
if (*Message_Ptr == 0)
return 0;
while (length && *Message_Ptr) {
copy_to_user(buffer++, *(Message_Ptr++), length--);
bytes_read++;
}
return bytes_read;
}
static ssize_t device_write(struct file *file, const char *buffer,
size_t length, loff_t *offset)
{
int i;
copy_from_user(Message, buffer, length);
Message_Ptr = Message;
return i;
}
struct file_operations Fops = {
read: device_read,
write: device_write,
open: device_open,
release: device_release
};
init init_module()
{
Major = module_register_chrdev(0, DEVICE_NAME, &Fops);
if (Major < 0) {
printk ("%s device failed with %d\n",
"Sorry, registering the character",
Major);
return Major;
}
printk ("%s The Major device number is %d.\n",
"Registeration is a success.",
Major);
printk("If you want to talk to the device driver,\n");
printk("you'll have to create a device file.\n");
printk("We suggest you use:\n");
printk("mknod <name> c %d <minor>\n", Major);
printk("You can try different minor numbers %s",
"and see what happens.\n");
return 0;
}
void cleanup_module()
{
int ret;
ret = module_unregister_chrdev(Major, DEVICE_NAME);
if (ret < 0)
printk("Eror in unregister_chrdev: %d\n", ret);
}
下面有出错贴图 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?注册
×
|