// 从网上看到一个代码, 解释ET和LT的区别, 比较生动 // 拷贝可以直接编译 g++ -g -Wall aaa.cpp #include <stdio.h> #include <iostream> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> using namespace std; #define MAXLINE 4 void setnonblocking (int sock) { int opts; opts = fcntl (sock, F_GETFL); if (opts < 0) { cout << "fcntl(sock,GETFL)" << endl; exit (1); } opts = opts | O_NONBLOCK; if (fcntl (sock, F_SETFL, opts) < 0) { cout << "fcntl(sock,SETFL,opts)" << endl; exit (1); } }; int main(int argc, char *argv[]) { int epfd = epoll_create(256); int fds[2]; pipe(fds); setnonblocking (fds[0]); int i, n; char line[MAXLINE]; struct epoll_event ev, events[20]; int nfds; int ret; int fk = fork(); if (!fk) { //printf("writing something : %d/n", fds[1]); for(;;) { ret = write(fds[1], "123456", 6); printf("/nwrite size n = %d, content= [123456] ", ret); cout << endl; sleep(2); } } // 改动这里,看到的结果是不一样的 ev.events = EPOLLIN | EPOLLET; //ev.events = EPOLLIN; ev.data.fd = fds[0]; ret = epoll_ctl (epfd, EPOLL_CTL_ADD, fds[0], &ev); //printf("ctl ret = %dn", ret); cout << endl; for(;;) { nfds = epoll_wait (epfd, events, 20, -1); for (i = 0; i < nfds; ++i) { //printf("reading something from fds=: %d", fds[0]); cout << endl; if (events[i].events & EPOLLIN) { //printf("reading something : %dn", fds[0]); if ((n = read (fds[0], line, sizeof(line))) < 0) { printf("are you kidding? %d", (errno)); cout << endl; exit(1); } else if (n == 0) { printf("read 0 bytes."); cout << endl; exit(1); } printf("read size n = %d, content= [", n); int j; for(j = 0; j < n; j++) { printf("%c", line[j]); } cout <<"]"<< endl; //line[n] = ' '; //printf("read : %sn", line); //memset(line, 0, sizeof(line)); } } } }