barunparichha |
02-15-2013 07:30 AM |
CHAR driver's open function issue
I have written my sample char driver code where a dynamic device node /dev/testNode is created and I am trying to open this from a program in user space. But I am not getting "DEVICE OPENED ...." message in my log. So I am not sure if my open function "myopen" is called.
And help will be appreciated.
test.c :
Code:
#include<linux/module.h>
#include<linux/init.h>
#include<linux/fs.h>
#include<linux/cdev.h>
#include<linux/delay.h> //msleep
#include<linux/device.h> //device_create
#define COUNT 1
#define NAME "testNode"
static struct class *cl;
static struct cdev *cdev;
dev_t dev;
int myopen(struct inode *inode, struct file *file)
{
int minor=MINOR(inode->i_rdev);
int major=MAJOR(inode->i_rdev);
printk(KERN_ALERT "DEVICE OPENED : major=%d minor=%d",major, minor);
msleep(1);
return 0;
}
static struct file_operations fops = {
.owner=THIS_MODULE,
.open=myopen,
};
static int start()
{
int res;
res=alloc_chrdev_region(&dev, 0, COUNT, NAME);
if(res <0)
{
printk(KERN_ALERT "Unable to allocate space");
return res;
}
else
printk(KERN_ALERT " Got Major=%d Minor=%d", MAJOR(dev), MINOR(dev));
cdev = cdev_alloc();
cdev->owner=THIS_MODULE;
cdev->ops=&fops;
res=cdev_add(cdev, dev, COUNT);
//Creating device node for major number we got
cl = class_create(THIS_MODULE,NAME);
if(IS_ERR(cl))
{
printk(KERN_ALERT "device class NOT created ...");
unregister_chrdev_region(cdev->dev,COUNT);
cdev_del(cdev);
return -1;
}
else
printk(KERN_ALERT "device class created ...");
if (device_create(cl, NULL, cdev->dev, NULL, NAME) ==NULL)
{
class_destroy(cl);
unregister_chrdev_region(cdev->dev,COUNT);
return -1;
}
printk(KERN_ALERT "START MODULE ...");
return 0;
}
static void leave()
{
printk(KERN_ALERT "LEAVING MODULE ... %d %d",MAJOR(cdev->dev),MINOR(cdev->dev));
device_destroy(cl, dev);
class_destroy(cl);
cdev_del(cdev);
unregister_chrdev_region(cdev->dev,COUNT);
}
module_init(start);
module_exit(leave);
MODULE_LICENSE("GPL");
MODULE_OWNER("Barun Kumar Parichha");
Makefile:
Code:
obj-m +=test.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
My User space C code to open /dev/testNode:
Code:
#include<stdio.h>
int main()
{
FILE * fd;
fd=fopen("/dev/testNode","r");
if(fd <0)
{
printf("\nError opening node ");
perror("fopen");
return 0;
}
else
printf("\n SUCCESS");
return 0;
}
|