一个由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;
}

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值