CODE: # include
# Include
# Include
# Include
# Include
# Include
# Include
MODULE_LICENSE ("GPL ");
Int hello_major= 252;
Int hello_minor = 0;
Int number_of_devices = 1;
Char data [50] = "foobar not equal to barfoo ";
Struct cdev;
Dev_t dev = 0;
Static int hello_open (struct inode * inode, struct file * file)
{
Printk (KERN_INFO "Hey! Device opened \ n ");
Return 0;
}
Static int hello_release (struct inode * inode, struct file * file)
{
Printk (KERN_INFO "Hmmm... device closed \ n ");
Return 0;
}
Ssize_t hello_read (struct file * filp, char * buff, size_t count, loff_t * offp)
{
Ssize_t result = 0;
If (copy_to_user (buff, data, sizeof (data)-1 ))
Result =-EFAULT;
Else
Printk (KERN_INFO "wrote % d bytes \ n", count );
Return result;
}
Ssize_t hello_write (struct file * filp, const char * buf, size_t count, loff_t * f_pos)
{
Ssize_t ret = 0;
Printk (KERN_INFO "Writing % d bytes \ n", count );
If (count> 127) return-ENOMEM;
If (count <0) return-EINVAL;
If (copy_from_user (data, buf, count )){
Ret =-EFAULT;
}
Else {
Data [127] = '\ 0 ';
Printk (KERN_INFO "Received: % s \ n", data );
Ret = count;
}
Return ret;
}
Struct file_operations hello_fops = {
. Owner = THIS_MODULE,
. Open = hello_open,
. Release = hello_release,
. Read = hello_read,
. Write = hello_write
};
Struct class * my_class;
Static void char_reg_setup_cdev (void)
{
Int error, devno = MKDEV (hello_major, hello_minor );
Cdev_init (& cdev, & hello_fops );
Cdev. owner = THIS_MODULE;
Cdev. ops = & hello_fops;
Error = cdev_add (& cdev, devno, 1 );
If (error)
Printk (KERN_NOTICE "Error % d adding char_reg_setup_cdev", error );
/* Creating your own class */
My_class = class_create (THIS_MODULE, "farsight_class"); // add by lht
If (IS_ERR (my_class )){
Printk ("Err: failed in creating class. \ n ");
Return;
}
/* Register your own device in sysfs, and this will cause udevd to create corresponding device node */
Class_device_create (my_class, NULL, devno, NULL, "farsight_dev ");
// Device_create (my_class, NULL, devno, "farsight_dev ");
}
Static int _ init hello_2_init (void)
{
Int result;
Dev = MKDEV (hello_major, hello_minor );
Result = register_chrdev_region (dev, number_of_devices, "test ");
If (result <0 ){
Printk (KERN_WARNING "hello: can't get major number % d \ n", hello_major );
Return result;
}
Char_reg_setup_cdev ();
Printk (KERN_INFO "char device registered \ n ");
Return 0;
}
Static void _ exit hello_2_exit (void)
{
Dev_t devno = MKDEV (hello_major, hello_minor );
Cdev_del (& cdev );
Unregister_chrdev_region (devno, number_of_devices );
Class_device_destroy (my_class, devno );
Class_destroy (my_class );
}
Module_init (hello_2_init );
Module_exit (hello_2_exit); v |