Programación de red Linux: disparador horizontal / disparador de borde

Dibujaré directamente

#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>


using namespace std;

#define MAXLINE 10
#define MAX_OPEN 10

#define PIPE_READ 0
#define PIPE_WRITE 1


int
main(int argc, char*argv[])
{
	pid_t pid;
	int i;
	char val = 'a', buf[MAXLINE];
	int pipefd[2];
	if (pipe(pipefd) < 0){
		perror("pipe error");
		exit(1);
	}

	pid = fork();

	if(pid < 0){
		perror("fork error");
		exit(1);
	}else if(pid == 0){ // son write
		close(pipefd[PIPE_READ]);
		while(true){
			for(i=0; i<MAXLINE/2; i++)
				buf[i] = val;
			buf[i-1] = '\n';
			// aaaa\n
			val++;
			for( ; i<MAXLINE; i++)
				buf[i] = val;
			buf[i-1] = '\n';
			// bbbb\n
			val++;
			write(pipefd[PIPE_WRITE], buf, MAXLINE);
			sleep(5);
		}
		
		close(pipefd[PIPE_WRITE]);

	}else{ // parent read
		struct epoll_event event;
		struct epoll_event resevent[MAX_OPEN];
		int ret, len, efd, nready;

		close(pipefd[PIPE_WRITE]);

//		event.events = EPOLLIN | EPOLLET; 	// EPOLL ET
		event.events = EPOLLIN;  			// EPOLL LT
		event.data.fd = pipefd[PIPE_READ];

		efd = epoll_create(MAX_OPEN);
		if(efd < 0){
			perror("epoll create error");
			exit(1);
		}
		
		ret = epoll_ctl(efd, EPOLL_CTL_ADD, pipefd[PIPE_READ], &event);
		if(ret < 0){
			perror("pipefd read add error in epoll_ctl");
			exit(1);
		}

		while(true){
			nready = epoll_wait(efd, resevent, MAX_OPEN, -1);
			printf("the read event number is %d\n", nready);
			if(resevent[0].data.fd == pipefd[PIPE_READ]){
				len = read(pipefd[PIPE_READ], buf, MAXLINE/2);
				write(STDOUT_FILENO, buf, len);
			}
		}

		close(pipefd[PIPE_READ]);
	}
	

	return 0;
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_44065088/article/details/109271117
Recomendado
Clasificación