您的位置:首页 > 其它

epoll的简单用法示例(程序还有bug,但只是为了示例epoll的用法就不改了)

2010-04-21 11:32 513 查看
//epoll用法示例
//创建PIPENUM个pipe和子进程,子进程负责写,父进程负责读
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define PIPENUM 4
int fdPipe[PIPENUM][2];
int createPipe(void)
{
int i, ret;
for (i = 0; i < PIPENUM; i++) {
ret = pipe(fdPipe[i]);
if (ret == -1)
return -1;
}
return 0;
}
int childWork(int index)
{
int i;
for (i = 0; i < PIPENUM; i++) {
if (i != index) {
close(fdPipe[i][0]);
close(fdPipe[i][1]);
} else {
close(fdPipe[i][0]);
}
}
srand(getpid());
int sleepers = 3 + rand() % 8;
sleep(sleepers);
char buf[256];
sprintf(buf, "hello, this is process %d.", getpid());
int ret = write(fdPipe[index][1], buf, strlen(buf)+1);
if (ret == -1)
return ret;
return 0;
}
int fatherWork(void)
{
int i;
for (i = 0; i < PIPENUM; i++) {
close(fdPipe[i][1]);
}
int ret = fatherActualWork();
if (ret == -1) {
printf("pollo fail/n");
return -1;
}
return 0;
}

int fatherActualWork(void)
{
int i;
int ret;
char buf[256];
int epfd=epoll_create(PIPENUM);
if( -1==epfd )
{
perror("epoll_create");
return -1;
}
struct epoll_event epe[PIPENUM], rev;
for( i=0 ; i<PIPENUM ; i++ )
{
epe[i].events=EPOLLIN;
epe[i].data.fd=fdPipe[i][0];
ret=epoll_ctl(epfd, EPOLL_CTL_ADD, fdPipe[i][0], &epe[i]);
if( -1==ret )
{
perror("epoll_ctl");
return -1;
}
}
while( 1 )
{
ret=epoll_wait(epfd, &rev, 1, -1);
if( ret==-1 )
{
perror("epoll_wait");
return -1;
}
if( rev.events&EPOLLIN==EPOLLIN )
{
memset(buf, 0, 256);
read(rev.data.fd, buf, 256);
printf("%s/n", buf);
}
}

}
int main(void)
{
int ret = createPipe();
if (ret == -1)
exit(1);
int i;
pid_t pid;
for (i = 0; i < PIPENUM; i++) {
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
ret = childWork(i);
if (ret == -1) {
printf("write fail/n");
sleep(100);
exit(1);
}
exit(0);
}
}
ret = fatherWork();
if (ret == -1) {
printf("read fail/n");
exit(1);
}
exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐