IOCTL写崩溃

时间:2013-03-26 03:40:38

标签: linux-kernel kernel ioctl

我正在尝试在内核空间中实现ioctl以在寄存器中写入一些日期,我在ioctl的cmd中崩溃了。

以下是我的代码:

内核方面:

static struct file_operations fops = {
.compat_ioctl = device_ioctl
};

int device_ioctl(struct inode *inode, struct file *filep, 
                 unsigned int cmd, unsigned long arg)
{

    int len = 200;

    printk (KERN_INFO "In Device_ioctl !!\n");
    switch(cmd)
    {
    case IOCTL_WRITE_REG:
        write_ioctl((unsigned long *)arg);
        break;

    default:
        printk (KERN_INFO "default\n");
        return -ENOTTY;
    }
    printk (KERN_INFO "device_ioctl out\n");
    return len;
}

用户端

#define IOCTL_WRITE_REG _IOW(MAJOR_NUM, 1, int *)
void write_to_device(int write_fd)
{

    int retval;
    unsigned int to_write1 = 1;

    retval = ioctl(write_fd, IOCTL_WRITE_REG, &to_write1);
    if(retval < 0)
    {
        printf("fd: %d, write error: %d\n", write_fd, errno);
        exit(-1);
    }
}

它没有进入device_ioctl函数, 我哪里错了?

1 个答案:

答案 0 :(得分:3)

我几乎没有注意到的事情:

  • 您需要使用unlocked_ioctl代替compat_ioctlcompat_ioctl允许32位用户空间程序在64位内核上调用ioctl调用。
  • ioctl处理函数的签名不正确(对于unlocked_ioctl)。预期的签名是:

    long (*unlocked_ioctl) (struct file * filep, unsigned int, unsigned long);
    

我还没有尝试过编译这段代码,但我认为这应该可行:

static struct file_operations fops = {
    .unlocked_ioctl = device_ioctl
};

long device_ioctl(struct file *filep, 
                  unsigned int cmd,
                  unsigned long arg)
{

    int len = 200;

    printk (KERN_INFO "In Device_ioctl !!\n");
    switch(cmd)
    {
    case IOCTL_WRITE_REG:
        write_ioctl((unsigned long *)arg);
        break;

    default:
        printk (KERN_INFO "default\n");
        return -ENOTTY;
    }
    printk (KERN_INFO "device_ioctl out\n");
    return len;
}