跳转至

09.阻塞和非阻塞

实验说明

在异步通知基础上修改

修改细节

在read函数中添加阻塞标志位判断即可

/* 实现对应的open/read/write等函数,填入file_operations结构体 */
static ssize_t gpio_key_drv_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
    int err;

    if ((g_key == 0) && (file->f_flags & O_NONBLOCK))
        return -EAGAIN;

    wait_event_interruptible(gpio_key_wait, g_key);
    err = copy_to_user(buf, &g_key, 4);
    g_key = 0;

    return 4;
}

应用代码

通过设置文件的阻塞或者非阻塞方式来达到检测

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <signal.h>

static int fd;

/*
 * ./button_test /dev/100ask_button0
 *
 */
int main(int argc, char **argv)
{
    int val;
    struct pollfd fds[1];
    int timeout_ms = 5000;
    int ret;
    int flags;

    int i;

    /* 1. 判断参数 */
    if (argc != 2) 
    {
        printf("Usage: %s <dev>\n", argv[0]);
        return -1;
    }


    /* 2. 打开文件 */
    fd = open(argv[1], O_RDWR | O_NONBLOCK);
    if (fd == -1)
    {
        printf("can not open file %s\n", argv[1]);
        return -1;
    }

    for (i = 0; i < 10; i++) 
    {
        if (read(fd, &val, 4) == 4)
            printf("get button: 0x%x\n", val);
        else
            printf("get button: -1\n");
    }

    flags = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);

    while (1)
    {
        if (read(fd, &val, 4) == 4)
            printf("get button: 0x%x\n", val);
        else
            printf("while get button: -1\n");
    }

    close(fd);

    return 0;
}