一个由poll引发的思考

晚上试了一波poll,写了一段巨烂的代码。

不过这段代码,让我猜到了printf和STDOUT_FILENO的关系,还有他缓冲的机制。

#include<stdio.h>
#include<unistd.h>
#include<poll.h>

#define TIMEOUT 5

char cReadBuffer[1024] = {'\0'};
int main(void)
{
    struct pollfd fds[2];
    int ret;
    int iReadLen;
    cReadBuffer[0] ='\0';

    while(1)
    {
        fds[0].events = POLLIN;
        fds[0].fd = STDIN_FILENO;

        fds[1].events = POLLOUT;
        fds[1].fd = STDOUT_FILENO;

        ret = poll(fds,2,TIMEOUT*1000);
        if (-1 == ret)
        {
            perror("poll");
            return 1;
        }

        if(!ret)
        {
            printf("%d seconds elapsed.\n",TIMEOUT);

            return 0;
        }

        if(fds[0].revents & POLLIN)
        {
            iReadLen = read(STDIN_FILENO,cReadBuffer,sizeof(cReadBuffer));
            if(-1 != iReadLen)
            {
                printf("read from STDIN:%s.",cReadBuffer);
            }
        }

        if(fds[1].revents & POLLOUT)
        {
            if('\0' != cReadBuffer[0])
            {
                if(-1 == write(STDOUT_FILENO,cReadBuffer,sizeof(cReadBuffer)) )
                {
                    perror("write");
                }
                cReadBuffer[0] = '\0';
            }
        }
    }
    return 0;
}

想了很久,终于搞懂为啥是这么显示的。


下面是一个简单的驱动程序示例,它实现了poll函数: ```c #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/poll.h> MODULE_LICENSE("GPL"); #define DEVICE_NAME "mypoll" static int my_poll(struct file *filp, poll_table *wait) { int mask = 0; poll_wait(filp, wait, &wait_queue); if (data_available()) { mask |= POLLIN | POLLRDNORM; } return mask; } static struct file_operations fops = { .owner = THIS_MODULE, .poll = my_poll, }; static int __init mypoll_init(void) { int ret; ret = register_chrdev(0, DEVICE_NAME, &fops); if (ret < 0) { printk(KERN_ALERT "Failed to register device: %s\n", DEVICE_NAME); return ret; } printk(KERN_INFO "Device registered: %s\n", DEVICE_NAME); return 0; } static void __exit mypoll_exit(void) { unregister_chrdev(0, DEVICE_NAME); printk(KERN_INFO "Device unregistered: %s\n", DEVICE_NAME); } module_init(mypoll_init); module_exit(mypoll_exit); ``` 在这个示例中,我们实现了一个名为my_poll的函数,它接受两个参数:一个指向文件结构体的指针filp和一个指向poll_table的指针wait。poll_table是一个用于等待事件的数据结构,它包含一个或多个等待队列。 在my_poll函数中,我们使用了poll_wait宏将当前进程加入等待队列中。如果数据可用,则设置mask变量中的POLLIN和POLLRDNORM标志,并返回mask值。 在初始化函数中,我们使用register_chrdev函数注册设备,并将my_poll函数指定为poll操作的回调函数。 在卸载函数中,我们使用unregister_chrdev函数注销设备。 注意:这个示例中的data_available函数没有被定义。它应该是一个用于检查数据是否可用的函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值