该进程为rile,利用epoll接收串口数据,接收rilc进程发来的命令。
while(1)
{
int nfds = epoll_wait(efd,events,MAXEVENTS,20);//
printf("nfds=%d\n",nfds);
int i;
for(i=0;i<nfds;i++)
{
if(events[i].data.fd==listen_fd)
{
printf("accept\n");
com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
event_socket.data.fd = com_fd;
event_socket.events = EPOLLIN|EPOLLET;
epoll_ctl(efd,EPOLL_CTL_ADD,com_fd,&event_socket);
}
else if(events[i].data.fd==fd)
{
bzero(buff_send,20);
nread = read(events[i].data.fd,buff_send,20);
if(nread>0)
{
tcdrain(fd);
tcflush(fd,TCIOFLUSH);
printf("nread=%d,buff_send=%s\n",nread,buff_send);
}
}
else if(events[i].data.fd==com_fd)
{
memset(recv_buf,0,1024);
int num=read(com_fd,recv_buf,sizeof(recv_buf));
printf("message from client %d:%s\n",num,recv_buf);
write(com_fd,buff_send,sizeof(buff_send));
event_socket.data.fd = com_fd;
event_socket.events = EPOLLIN|EPOLLET;
epoll_ctl(efd,EPOLL_CTL_DEL,com_fd,&event_socket);
}
else{
printf("do nothing\n");
}
}
代码里不能同一时刻调用多个epoll_wait
通过从内核获取的事件判断是哪个描述符发生了事件作相应处理。对于socket进程通信,先等待连接事件的发生,再创建新epoll事件用于读取,读取完后需要注销掉epoll读取事件