#include <stdio.h>
#include <fcntl.h>
#include <sys/select.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUF_SIZE 1024
int main()
{
int fds[2];
char buf[BUF_SIZE];
bzero(buf, BUF_SIZE);
int i, rc, maxfd;
fd_set watchset;
fd_set inset;
if((fds[0] = open("p1", O_RDONLY|O_NONBLOCK)) < 0)
{
perror("open");
exit(1);
}
if((fds[1] = open("p2", O_RDONLY|O_NONBLOCK)) < 0)
{
perror("open");
exit(1);
}
FD_ZERO(&watchset);
FD_SET(fds[0], &watchset);
FD_SET(fds[1], &watchset);
maxfd = (fds[0] > fds[1] ? fds[0] : fds[1]);
while(FD_ISSET(fds[0], &watchset) ||
FD_ISSET(fds[1], &watchset))
{
inset = watchset;
if(select(maxfd, &inset, NULL, NULL, NULL) < 0)
{
perror("select");
exit(1);
}
for(i = 0; i < 2; i++)
{
if(FD_ISSET(fds[i], &inset))
{
rc = read(fds[i], buf, BUF_SIZE);
if(rc < 0)
{
perror("read");
exit(1);
}
else if(!rc)
{
close(fds[i]);
FD_CLR(fds[i],&watchset);
}
else
{
buf[rc] = 0;
printf("read %s", buf);
}
}
}
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/poll.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
struct pollfd fds[2];
char buf[4096];
int i, rc, ret;
if((fds[0].fd = open("p1", O_RDONLY|O_NONBLOCK)) < 0)
{
perror("open");
exit(1);
}
if((fds[1].fd = open("p2", O_RDONLY|O_NONBLOCK)) < 0)
{
perror("open");
exit(1);
}
fds[0].events = POLLIN;
fds[1].events = POLLIN;
while(fds[0].events || fds[1].events)
{
if((ret = poll(fds, 2, -1)) < 0)
{
perror("poll");
exit(1);
}
for(i = 0; i < 2; i++)
{
if(fds[i].revents)
{
rc = read(fds[i].fd, buf, sizeof(buf) - 1);
if(rc < 0)
{
perror("read");
exit(1);
}
else if(rc == 0)
{
fds[i].events = 0;
}
else
{
buf[rc] = 0;
printf("read %s", buf);
}
}
}
}
}
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/poll.h>
#include <sys/epoll.h>
void addEvent(int, char *);
int main(int argc, char * argv[])
{
char buf[4096];
int i, rc;
int epfd;
struct epoll_event events[2];
int num;
int numFds;
epfd = epoll_create(2);
if(epfd < 0)
{
perror("epoll_create");
exit(1);
}
addEvent(epfd, "p1");
addEvent(epfd, "p2");
numFds = 2;
while(numFds)
{
if((num = epoll_wait(epfd, events, 2, -1)) < 0)
{
perror("epoll_wait");
exit(1);
}
for(i = 0; i < num; i++)
{
rc = read(events[0].data.fd, buf, sizeof(buf) - 1);
if( rc < 0 )
{
perror("read");
exit(1);
}
else if(!rc)
{
if(epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &events[i]))
{
perror("epoll_ctl");
exit(1);
}
}
else
{
buf[rc] = 0;
printf("read %s", buf);
}
}
}
close(epfd);
}
void addEvent(int epfd, char * filename)
{
int fd;
struct epoll_event event;
if((fd = open(filename, O_RDONLY|O_NONBLOCK)) < 0)
{
perror("error!");
exit(1);
}
event.events = EPOLLIN;
event.data.fd = fd;
if(epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event))
{
perror("epoll_ctl");
exit(1);
}
}