Linux Char Driver:阻止ioctl调用

时间:2012-02-24 06:49:11

标签: linux linux-kernel linux-device-driver ioctl

我是驱动程序开发的新手,我正在尝试编写一个简单的char驱动程序,它具有ioctl,允许用户进程获取我的char驱动程序在上次读写时所用的时间(timespec)。

long charmem_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) {
    struct charmem_dev *dev = filp->private_data;

    if (down_interruptible(&dev->sem)) {
        printk(KERN_WARNING "I got booted!!\n");
        return -ERESTARTSYS;
    }

    printk(KERN_WARNING "charmem: in ioctl; cmd = %d, arg = %d\n", (int)cmd, (int)arg);
    switch(cmd) {
        case IOCTL_GET_LAST_READ_TIME:
            printk("charmem_ioctl: returning last read time delta, exiting...\n");
            up(&dev->sem);
            return dev->last_read_delta.tv_nsec;
            break;

        case IOCTL_GET_LAST_WRITE_TIME:
            printk("charmem_ioctl: returning last write time delta, exiting...\n");
            up(&dev->sem);
            return dev->last_write_delta.tv_nsec;
            break;

        case IOCTL_RESET_READ: /*return read-pointer to the start of buffer*/
            dev->rp = dev->buffer;
            break;
        case IOCTL_RESET_WRITE: /*return write-pointer to the start of buffer*/
            dev->wp = dev->buffer;
            break;
        case IOCTL_LOAD_BUFFER_TO_CACHE:
            load_buffer_to_cache(dev->buffer, dev->buffer_size);
            break;
        default:
            printk("charmem_ioctl: invalid ioctl command, exiting...\n");
            up(&dev->sem);
            return -EFAULT;
    }

    up(&dev->sem);
    return 0;
}

struct file_operations charmem_fops = {
    .owner = THIS_MODULE,
    .llseek = no_llseek,
    .read = charmem_read,
    .write = charmem_write,
    .unlocked_ioctl = charmem_ioctl,
    .open = charmem_open,
    .release = charmem_release,
};

main.c - 测试我的char设备的用户程序:

int fd = 0, ret = 0;
fd = open("/dev/charmem0", O_RDWR);
if (fd < 0) {
    printf("/dev/charmem0  unable to access (fd = %d)... EXITING\n", fd);
    return -1;
}

ret = write(fd,msg1,10);
ret = read(fd,user_buffer,10);
read_delta = ioctl(fd, IOCTL_GET_LAST_READ_TIME);
printf("read_delta : %d\n ", read_delta);
write_delta = ioctl(fd, IOCTL_GET_LAST_WRITE_TIME);
printf("write_delta : %d\n ", write_delta);

main.c是测试我的char设备的程序;打印出read_delta值后程序阻塞,我假设它在ioctl上阻塞。我的代码中我做错了什么?

1 个答案:

答案 0 :(得分:2)

我没有看到代码中信号量的上/下有任何问题。程序阻塞的最可能的地方是对down_interruptible()的调用。如果你按下control-c,那将强制down_interruptible返回,你应该在dmesg或你的控制台或系统日志中看到你的“我被启动”的printk。然后任务是弄清楚你的驱动程序中的其他东西是持有那个信号量。

另一个想法发生在我身上...... printf是缓冲的。因此,您的GET_LAST_WRITE_TIME ioctl可能会返回,并且输出位于stdout缓冲区中,并且您的程序实际上停留在某些代码上。建议在printf之后添加fflush(stdout)(“写delta'以消除这种可能性。

迈克尔