【发布时间】:2011-11-15 04:05:29
【问题描述】:
我正在从管道读取未知数量的消息。但是,读取是阻塞的。我尝试使用以下代码将读取设置为非阻塞。但是,这会导致读取错误和进程无法一直读取。
// Set pipe to non-blocking
sleep(5);
fcntl(fd[index][0], F_SETFL, O_NONBLOCK);
如何在程序不挂起的情况下成功读取和打印所有消息? 这是导致问题的代码:
// Read every message
while((n = read(fd[index][0], &mymsg, sizeof(int))) == sizeof(int))
printf("process%d has received a message from process%d\n", index, mymsg);
【问题讨论】:
-
阅读 select、poll 和 epoll 的文档。
-
您遇到什么错误?当没有可读取的内容时,非阻塞套接字将始终返回“读取错误”。
-
@ZanLynx 没错。当启动足够的进程时。几个进程将退出并出现读取错误。