blockIO_unblockIO_async

linux kernel 阻塞IO/非阻塞IO/异步通知的编写,都分为三步:

  1. 创建 struct file_operations 变量

  2. 创建 阻塞IO/非阻塞IO/异步通知

  3. 唤醒

  4. 编写应用程序

阻塞IO

1. 创建 struct file_operations 变量

const struct file_operations xxx_fops = {
    .read    = xxx_read,
};

2. 创建阻塞IO

DECLARE_WAIT_QUEUE_HEAD(xxx_waitQueueHead); // 定义及初始化等待队列头

ssize_t xxx_read(struct file *file, char __user *buf, size_t size, loff_t *offset)
{
    unsigned char ret;

    if(file->f_flags & O_NONBLOCK)
    {
        // 非阻塞IO模式
    }
    else
    {
        // 阻塞IO模式
        DECLARE_WAITQUEUE(wq, current);            // 创建等待队列
        add_wait_queue(&xxx_waitQueueHead, &wq);   // 将 等待队列 加入 等待队列头
        set_current_state(TASK_INTERRUPTIBLE);
        schedule();                                // 睡眠,等待唤醒

        remove_wait_queue(&xxx_waitQueueHead, &wq);// 唤醒后,从 等待队列头 删除 等待队列
    }

    ......

    // 将内核空间kernel_buffer复制到用户空间buf
    ret = copy_to_user(buf, &kernel_buffer, size); 

    return 0;
}

3. 唤醒

唤醒步骤一般在中断处理函数或下半部函数中调用

4. 编写应用程序

非阻塞IO

1. 创建 struct file_operations 变量

2. 创建非阻塞IO

3. 唤醒

唤醒步骤一般在中断处理函数或下半部函数中调用

4. 编写应用程序

  • SELECT_METHOD

  • POLL_METHOD

异步通知

1. 创建 struct file_operations 变量

2. 创建异步通知

3. 唤醒

唤醒步骤一般在中断处理函数或下半部函数中调用

4. 编写应用程序

Last updated

Was this helpful?