#include <linux/module.h> #include <linux/fs.h> #include <linux/major.h> #include <linux/capability.h> #include <asm/uaccess.h> #include <linux/cdev.h> #include <linux/sem.h> #include <linux/vmalloc.h> #include <linux/ipc.h> #include <linux/delay.h> #include <linux/semaphore.h> int i,shmid; char a[10]=0; struct semaphore lock; static ssize_t sample_char_read(struct file * file, char __user * buf,size_t count, loff_t *ppos) { printk("sample_char2_read size(%ld)\n", count); return 0; } static ssize_t sample_char_write(struct file *filp, const char *buf,size_t size, loff_t *offp) { ///semaphore locking down(&lock); printk("sample_char_write size(%ld)\n", size); copy_from_user((void *) a,buf,size); printk("kernal=%s\n",a); msleep(5000); //semaphor unlock up(&lock); return size; } int sample_char_open(struct inode *inode, struct file *filp) { printk("sample_char_open\n"); //semaphore init sema_init(&lock, 1); return 0; } int sample_char_release(struct inode *inode, struct file *filp) { printk("sample_char_release\n"); return 0; } static struct file_operations sample_char_fops = { read:sample_char_read, write:sample_char_write, open:sample_char_open, release:sample_char_release, }; #define sample_major_number 89 #define max_minors 1 static struct cdev char_cdev; static dev_t dev; int init_module(void) { int ret = 0; dev = MKDEV(sample_major_number, 0); printk("\nLoading the sample char device driver\n"); ret = register_chrdev_region(dev,1, "sample_char"); if (ret) { printk("register_chrdev_region Error\n"); goto error; } cdev_init(&char_cdev, &sample_char_fops); ret = cdev_add(&char_cdev, dev,2); if (ret) { printk("cdev_add Error\n"); goto error_region; } return 0; error_region: unregister_chrdev_region(dev, max_minors); error: return ret; } void cleanup_module(void) { cdev_del(&char_cdev); unregister_chrdev_region(dev, max_minors); printk("\nUnloading the sample char device driver\n"); } TEST FILE #include<stdio.h> #include <fcntl.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> int main(int argc ,char *argv[]) { char buf[100] ; char i = 0; int g; memset(buf, 0, 100); printf("Input: %s\n", argv[1]); int fp = open("/dev/sample_char", O_RDWR); if(fp<0) { perror("not sucess"); } i=fork(); if(i==0) { g=write(fp,argv[1], strlen(argv[1])); } else { g=write(fp,argv[2], strlen(argv[2])); wait(0); } } MAKE FILE obj-m += semaphore.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean test:app.c COMPILATION OF CODE gcc -o test app.c
Showing posts with label semaphore. Show all posts
Showing posts with label semaphore. Show all posts
Sunday, 18 May 2014
Character device driver using semaphore mechanism in linux
Subscribe to:
Posts (Atom)