epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event)为何老返回-1

redong 2012-05-31 05:39:49
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>

#include <sys/poll.h>

void addEvent(int epfd, char* filename)
{
int ret;
int fd;
struct epoll_event event;

if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) < 0)
{
perror("open");
exit(1);
}

event.events = EPOLLIN;
event.data.fd = fd;

ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
printf("epoll_ctl(ADD) return[%d]\n", ret);
if (ret)
{
perror("epoll_ctl(ADD)");
exit(1);
}

}

int main(void)
{
char buf[4096];
int i, rc;
int epfd;
struct epoll_event events[2];

int num;
int numFds;

epfd = epoll_create(2);
if (epfd < 0)
{
perror("epoll_create");
return 1;
}

/*open both pipes and add them to the epoll set*/

addEvent(epfd, "p1");

addEvent(epfd, "p2");

/*continue while we have one or more file descriptors to watch*/

numFds = 2;

while (numFds)
{
if ((num = epoll_wait(epfd, events, sizeof(events)/sizeof(*events), -1)) <= 0)
{
perror("epoll_wait");
return 1;
}

for (i = 0; i<num; i++)
{
/*events[i].data.fd is ready for reading*/

rc = read(events[i].data.fd, buf, sizeof(buf)-1);
if (rc < 0)
{
perror("read");
return 1;
}
else if (!rc)
{
/*this pipe has been closed, don't try to read from it again*/
if (epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, &events[i]))
{
perror("epoll_ctl(DEL)");
return 1;
}

close(events[i].data.fd);

numFds--;


}
else
{
buf[rc] = '\0';
printf("read: %s", buf);
}

}
}

close(epfd);

return 0;
}

哪位大虾, 帮一下.
为什么这句老是返回-1 ???
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
...全文
710 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
glacierful 2012-09-17
  • 打赏
  • 举报
回复
我用串口的fd,epoll_ctl时,也报了这个错误。难道串口也不行?
redong 2012-06-01
  • 打赏
  • 举报
回复
perror提示: epoll_ctl(ADD): Operation not permitted
qq120848369 2012-06-01
  • 打赏
  • 举报
回复
结论就是epoll不支持文件fd, 还真没注意过, 因为网络发文件都是注册socket的write事件来触发的, 而且曾经也尝试过select文件fd是可以的,偏偏epoll不支持。
qq120848369 2012-05-31
  • 打赏
  • 举报
回复
perror 看错误?

23,120

社区成员

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

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