poll函数操作fd,等待读取失败.怎么修改程序?

learnxml163 2010-11-25 02:07:10
1. 创建两个fifo,用于读入数据.
2. main函数进入poll循环,监视这两个fd
3. 当poll返回>0的时候,读取管道的内容并打印

从命令行,用echo命令向myfifo1/myfifo2发送数据,我期待a.out立刻将数据打印出来。但是a.out阻塞了,什么输出也没有。
我的代码问题在哪里?


#include<sys/stat.h>
#include<sys/types.h>
#include<poll.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
char buf[20]={0};
int f(const char* fifo){
unlink(fifo);
mkfifo(fifo,0666);
return open(fifo,O_RDONLY);
}
void g(int fd){
read(fd,buf,sizeof(buf));
printf("read done:%s\n",buf);
}
int main(void){
int fd1=f("myfifo1");
int fd2=f("myfifo2");
if(!(fd1||fd2))return 1;
struct pollfd myfifo[2];
myfifo[0].fd=fd1;
myfifo[0].events=POLLIN;
myfifo[1].fd=fd2;
myfifo[1].events=POLLIN;
int ret;
while(ret=poll(myfifo,fd2+1,-1)){
if(ret<=0){
perror("poll error\n");
return 1;
}else{
if( myfifo[0].revents & POLLIN){g(fd1);}
else if(myfifo[0].revents & POLLIN){g(fd2);}
}
}
close(fd1);
close(fd2);
return 0;
}
...全文
110 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
guoxuqu 2010-11-25
  • 打赏
  • 举报
回复
还有一个问题。open(fifo,O_RDONLY);要改为oopen(fifo,O_RDONLY|O_NONBLOCK);
不然会阻塞在这里。
guoxuqu 2010-11-25
  • 打赏
  • 举报
回复
#include <poll.h>

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

#define _GNU_SOURCE
#include <poll.h>

int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask);

DESCRIPTION
poll() performs a similar task to select(2): it waits for one of a set
of file descriptors to become ready to perform I/O.

The set of file descriptors to be monitored is specified in the fds
argument, which is an array of structures of the following form:

struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};

The caller should specify the number of items in the fds array in nfds.
上面是man手册关于poll的说明,最后一句是说poll第二个参赛应该是数组fds的大小
guoxuqu 2010-11-25
  • 打赏
  • 举报
回复
while(ret=poll(myfifo,fd2+1,-1))错误应为while(ret=poll(myfifo,2,-1))
learnxml163 2010-11-25
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 justkk 的回复:]

while(ret=poll(myfifo,fd2+1,-1))
===》
while((ret=poll(myfifo,fd2+1,-1)))
[/Quote]

谢谢,我按照你说的改了。但是问题仍然存在。
justkk 2010-11-25
  • 打赏
  • 举报
回复
while(ret=poll(myfifo,fd2+1,-1))
===》
while((ret=poll(myfifo,fd2+1,-1)))

23,223

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧