ioctl以奇怪的方式打电话

时间:2014-04-18 17:31:13

标签: c linux device-driver

我是Linux驱动程序新手,我正在学习ioctl调用。 我为测试命令做了一个简单的测试程序,如下所示

内核模块:

  #include<linux/module.h>
  #include<linux/kernel.h>
  #include<linux/init.h>
  #include<linux/ioctl.h>
  #include<linux/cdev.h>
  #include<linux/fs.h>
  #include<linux/device.h>
  MODULE_LICENSE("GPL");
  static char kernel[20];
  struct class *c_class;
  dev_t dev; 
  struct cdev mcdev;

  static int my_open(struct inode* inode, struct file *file)
   {
     printk("opened\n");
     return 0;
   }

   static ssize_t my_write(struct file * file,const char * user,size_t count,loff_t * offset) 
   {
      copy_from_user(kernel, user, count);
      printk("%s\n",kernel); 
      return 0;
   }
   /*
       check for command 2 as unsigned int
   */
   static int ioctl_call(struct file *f, unsigned int cmd, unsigned long arg) 
    {
      printk("cmd = %c\n",cmd);
      switch(cmd)
    {
    case 1:
        printk("case11\n");
        break;
    case 2:
        printk("case12\n");
        break;
    default:
        printk("case3\n");
        break;  
   }

    return 0; 
   }

   static struct file_operations fops = {
.open = my_open,
.write = my_write,
.unlocked_ioctl = ioctl_call,
.owner = THIS_MODULE,
   };

   static int __init inin(void)
    {
 printk("sdfsdfsdf\n");
 alloc_chrdev_region(&dev, 0, 1, "hello");
 cdev_init(&mcdev, &fops);
 cdev_add(&mcdev, dev, 1); 
 c_class = class_create(THIS_MODULE, "claaass");
 device_create(c_class, NULL, dev, NULL, "devieee");
 return 0;
    }
    module_init(inin);

    static void __exit outpu(void)
    {
      device_destroy(c_class, dev);
      class_destroy(c_class);
      cdev_del(&mcdev);
      unregister_chrdev_region(dev, 1);
    }
     module_exit(outpu);

应用程序:

  #include<stdio.h>
  #include<stdlib.h>
  #include<fcntl.h>
  #include<linux/ioctl.h>
  int main()
  {
    int fd,a;
    char to_kernel[100]="hello how are you";
    fd = open("/dev/devieee", O_WRONLY);
    if( fd < 0)
     {
       printf("Unable to open the device\n");
       exit(0);
     }
    write(fd,to_kernel,20);
    if(!(a=ioctl(fd, 2, to_kernel)))
       printf("a = %d called\n",a);
    printf("outside a = %d",a);
    return 0;
   }

我想在驱动程序中打印案例2,但它从不调用ioctl,如果我在此ioctl应用程序中放入其他任何内容,它将打印出那个,但不是2。

0 个答案:

没有答案