weixin_慕哥3021856 的學(xué)生作業(yè):
epoll.c
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXEVENTS 10
#define FIFO "./fifo_epoll"
int main(int argc, const char *argv[])
{
int epfd, ret, fd;
int rbytes;
struct epoll_event eevent;
struct epoll_event ret_eev[MAXEVENTS];
char buffer[64] = {0};
epfd = epoll_create(1);
if (epfd == -1)
{
perror("[ERROR] epoll_create()");
exit(EXIT_FAILURE);
}
printf("epfd = %d\n", epfd);
fd = open(FIFO, O_RDONLY | O_NONBLOCK);
if (fd == -1)
{
perror("[ERROR] open()");
exit(EXIT_FAILURE);
}
eevent.events = EPOLLIN;
eevent.data.fd = fd;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &eevent);
if (ret == -1)
{
perror("[ERROR] epoll_ctl()");
exit(EXIT_FAILURE);
}
for (;;)
{
ret = epoll_wait(epfd, ret_eev, MAXEVENTS, 1000);
if (ret == -1)
{
perror("[ERROR] epoll_wait()");
exit(EXIT_FAILURE);
}
else if (ret == 0)
{
printf("Timeout\n");
}
else
{
// 循環(huán)處理事件
for (int i = 0; i < ret; i++)
{
int current_fd = ret_eev[i].data.fd;
rbytes = read(current_fd, buffer, sizeof(buffer)-1);
if (rbytes > 0)
{
buffer[rbytes] = '\0';
if (strcmp(buffer, "q") == 0 || strcmp(buffer, "Q") == 0)
{
close(current_fd);
epoll_ctl(epfd, EPOLL_CTL_DEL, current_fd, NULL);
printf("The fd[%d] was closed.\n", current_fd);
break;
}
printf("Read buffer: %s\n", buffer);
}
else if (rbytes == 0) // 寫(xiě)端關(guān)閉
{
close(current_fd);
epoll_ctl(epfd, EPOLL_CTL_DEL, current_fd, NULL);
break;
}
memset(buffer, 0, sizeof(buffer));
}
}
}
return 0;
}
namedpipe.c
#include
#include
#include
#include
#include
#include
#include
#define FIFO "./fifo_epoll"
int main(void)
{
int fd, ret;
char wbuf[64];
ssize_t wbytes;
memset(wbuf, 0, sizeof(wbuf));
ret = access(FIFO, F_OK);
if (ret == -1)
{
mkfifo(FIFO, 0666);
}
fd = open(FIFO, O_WRONLY);
if (fd == -1)
{
perror("[ERROR] open()");
exit(EXIT_FAILURE);
}
for (;;)
{
printf("Input: ");
fgets(wbuf, sizeof(wbuf), stdin);
wbuf[strlen(wbuf) - 1] = '\0';
wbytes = write(fd, wbuf, strlen(wbuf));
if (wbytes == -1)
{
perror("[ERROR] write()");
close(fd);
exit(EXIT_FAILURE);
}
if (strcmp(wbuf, "q") == 0 || strcmp(wbuf, "Q") == 0)
{
break;
}
memset(wbuf, 0, sizeof(wbuf));
}
close(fd);
return 0;
}