子进程往pipe管道写,父进程监听管道输入事件,从管道读取子进程发送的数据。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/epoll.h>
#define MSG_MAX_SIZE 100
void sys_error(const char *str)
{
perror(str);
exit(1);
}
int main(void)
{
int ret;
char buf[MSG_MAX_SIZE]; //message buffer
int fd[2];//pipe fd array,to restore the read & write end of the pipe.
ret = pipe(fd);//pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.
if (ret == -1)
sys_error("pipe open failure");
pid_t pid;
pid = fork();//create a child process
if (pid == -1)
sys_error("fork an sub process fail");
else if (pid == 0)//it is a child process. in this demo,child process act as a writor.
{
close(fd[0]); // child process close the read end;
int msg_no = 0;
while (1)
{
msg_no++;
sprintf(buf,"message no.%d",msg_no);
write(fd[1], buf, sizeof(buf));//write sth via the write end.
printf("%30s%s\n","child process send:",buf);
sleep(2);
}
}
else
{//it is the parent process, and acts as a reader.
close(fd[1]); //parent proc close the write end.
int epfd = epoll_create(512); // open an epoll file descriptor.
if (epfd == -1)
sys_error("epoll_create failure");
// interested event .
//pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.
struct epoll_event read_event;
read_event.events = EPOLLIN; //The associated file is available for read(2) operations.
read_event.data.fd = fd[0];//parent process will read via fd[0]
int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd[0], &read_event);
if (ret == -1)
sys_error("epoll_ctl failure");
struct epoll_event output_events[1]; //output parameters,to restore the I/O event associated fd
int all_events;
while (1)
{
all_events = epoll_wait(epfd, output_events, 1, 0); // wait for an I/O event on an epoll file descriptor
if (all_events == -1)
sys_error("epoll_wait failure");
else if (all_events > 0)//I/O event on an epoll file descriptor,read data via fd[0]
{
read(fd[0], buf, MSG_MAX_SIZE);
printf("%30s%s\n\n","parent process receive:",buf);
} else{
}
}
close(fd[0]);
close(epfd);
}
return 0;
}
运行结果: