0

我正在尝试在内核空间中实现 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 函数,我哪里出错了?

4

1 回答 1

3

我碰巧注意到的几件事:

  • 您需要使用unlocked_ioctl而不是compat_ioctl. compat_ioctl是允许 32 位用户空间程序调用ioctl64 位内核上的调用。
  • 您的 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;
}
于 2013-03-26T04:34:28.930 回答