#include #include #include #include #include #define MAGIC 'z' #define GET_DATA _IOR(MAGIC, 1, int *) #define SET_DATA _IOW(MAGIC, 2, int *) #define GET_SIZE _IOR(MAGIC, 3, int *) struct file_operations fops; static char array[80] = "HelloWorld"; static int major; int Mydevice_init_module(void) { printk("In init module"); major = register_chrdev(0,"Mydevice",&fops); printk("\nThe device is registered by Major no: %d",major); if(major == -1) printk("\nError in registering the module"); else printk("\n"); return 0; } void Mydevice_cleanup_module(void) { unregister_chrdev(major,"Mydevice"); printk("In cleanup module"); } static int my_open(struct inode *inode, struct file *file) { printk("\nMydevice: open"); return 0; } static int my_release(struct inode *inode, struct file *file) { printk("\nMydevide: release"); return 0; } static ssize_t my_read(struct file *file, char *buff, size_t n,loff_t *offset) { int position = (long)*offset; printk("\nMydevice: read"); copy_to_user(buff,array+position,n); return 0; } static ssize_t my_write(struct file *file, const char *buff, size_t n, loff_t *offset) { int position = (long)*offset; printk("\nMydevice: write"); copy_from_user(array+position,buff,n); return 0; } static loff_t my_lseek(struct file *file,loff_t offset,int whence) { printk("\nMydevice: lseek"); switch(whence) { case 0: file->f_pos = offset; //SEEK_SET break; case 1: file->f_pos = (file->f_pos) + offset; //SEEK_CUR break; case 2: file->f_pos = sizeof(array) - offset; //SEEK_END break; } return file->f_pos; } static int my_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) { switch(cmd) { case GET_DATA: printk("\nMydevice: ioctl: GET_DATA"); copy_to_user((char *)arg, array, 80); break; case SET_DATA: printk("\nMydevice: ioctl: SET_DATA"); copy_from_user(array, (char *)arg, 80); break; case GET_SIZE: printk("\nMydevice: ioctl: GET_SIZE"); *(int *) arg = sizeof(array); break; } return 0; } struct file_operations fops = { open: my_open, release: my_release, read: my_read, write: my_write, llseek: my_lseek, ioctl: my_ioctl, }; module_init(Mydevice_init_module); module_exit(Mydevice_cleanup_module); MODULE_LICENSE("GPL");