您的位置:首页 > 其它

epoll的LT和ET模式

2010-10-12 16:32 337 查看
// 从网上看到一个代码, 解释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
= ' ';
//printf("read : %sn", line);
//memset(line, 0, sizeof(line));
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: