linux epoll

今天,網上瀏覽一下,又看到了epoll話題,同時,也看了下例子數組

發現了一些之前牛牛寫的博文裏有些說法彷佛不太準確,可是,人家倒是是經過實例演示了app

但是,光有終端上的顯示結果,就去說明了本身定義的緣由也不穩當spa

一。進程

// epoll 標準讀取設備事件

//demo-read.cit

#include <stdio.h>io

#include <unistd.h>event

#include <sys/epoll.h>gcc

 

int main(void)file

{

    int epfd,nfds;

    struct epoll_event ev,events[5];//ev用於註冊事件,數組用於返回要處理的事件

    epfd = epoll_create(1);//只須要監聽一個描述符——標準輸入

    ev.data.fd = STDIN_FILENO;

    ev.events = EPOLLIN|EPOLLET;//監聽讀狀態同時設置ET模式

    epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev);//註冊epoll事件

    for(;;)

    {

        nfds = epoll_wait(epfd, events, 5, -1);

        for(int i = 0; i < nfds; i++)

        {

            if(events[i].data.fd==STDIN_FILENO)

                printf("Something happened with stdin!\n");

            //ev.data.fd = STDIN_FILENO;

            //ev.events = EPOLLIN|EPOLLET;                        //設置ET模式

            //epoll_ctl(epfd, EPOLL_CTL_MOD, STDIN_FILENO, &ev);    //重置epoll事件(ADD無效)

        }

    }

}

#gcc -o demo-read.o -c demo-read.c

#gcc -o demo-read demo-read.o

#./demo-read

abc
Something happened with stdin!

若是你打開註釋的話,每次讀取後,重置邊緣重發,就會不停地輸出

Something happened with stdin!
Something happened with stdin!
Something happened with stdin!
Something happened with stdin!
Something happened with stdin!

這個好理解,至關於每次都告訴epoll,「輸入緩衝有數據,就返回讀就緒」

這裏的緣由和結果都沒問題

 

二。

//epoll 標準輸出設備

#include <stdio.h>

#include <unistd.h>

#include <sys/epoll.h>

 

int main(void)

{

    int epfd,nfds;

    struct epoll_event ev,events[5];//ev用於註冊事件,數組用於返回要處理的事件

    epfd = epoll_create(1);//只須要監聽一個描述符——標準輸出

    ev.data.fd = STDOUT_FILENO;

    ev.events = EPOLLOUT|EPOLLET;//監聽寫狀態同時設置ET模式

    epoll_ctl(epfd, EPOLL_CTL_ADD, STDOUT_FILENO, &ev);//註冊epoll事件

    printf("begin to epoll\n");

    int count = 0;

    for(;;)

    {

        nfds = epoll_wait(epfd, events, 5, -1);

        for(int i = 0; i < nfds; i++)

        {

            if(events[i].data.fd==STDOUT_FILENO)

            {

                count++;

                printf("welcome to epoll's word!");

                //ev.data.fd = STDOUT_FILENO;

                //ev.events = EPOLLOUT|EPOLLET;//設置ET模式

                //epoll_ctl(epfd, EPOLL_CTL_MOD, STDOUT_FILENO, &ev);//重置epoll事件(ADD無效)

 

            }

        }

    }

}

#gcc -g -o demo-write.o -c demo-wirte.c

#gcc -g -o demo-write demo-write.o

#gdb

#file ./demo-write

(gdb)b 23

(gdb)r

(gdb)c

(gdb)c

(gdb)c

(gdb) p count
$1 = 3

看到沒有,這裏就不是說打印的信息沒有被清除緩衝,epoll_wait就掛起進程了。

事實上是,只要標準寫緩衝未滿,那麼epoll_wait就不會掛起!!!!

這裏就是網上信息的一個誤區。。。。

這裏打開註釋行後的效果就至關於在輸入後加入了換行,每次都能從寫緩衝區取出顯示在控制檯上

 

Finally:

有時候,老生常談仍是要談談啊。由於有些問題並非表面看到的那樣瓜熟蒂落。也就是說,大多數時候,你都會碰到坑,你一次能跨過去,也許下次就摔死在這裏啦

相關文章
相關標籤/搜索