我有一个选择和管道的问题。我试图创建3个子进程,每个进程都有一个管道向父进程发送消息。我正在使用select()
检查是否有任何fd准备就绪。我的问题是我总是从select()
获得非零返回值,所以我的循环不会终止。有人可以帮我弄这个吗?感谢点。
int pps[3][3]; //pipes
int highestFD=-1;
fd_set read_set;
for (i = 0;i<3;i++) {
if(pipe(pps[i]) != 0) {
exit(1);
}
int ret= fork();
if (ret== 0) {
close(STDOUT_FILENO);
close(pps[i][0]);
dup2(pps[i][1], 1);
write(1, "something", 100);
exit(0); //child process exit
}
if (ret > 0) {
close(pps[i][1]);
if (pps[i][0] > highestFD)
highestFD = pps[i][0];
}
}
while(1) {
FD_ZERO(&read_set);
for (i = 0;i<3;i++) {
FD_SET(pps[i][0], &read_set);
}
changedCount = 0;
changedCount = select(highestFD+1, &read_set, NULL, NULL, NULL);
if (changedCount <= 0) {
printf("exit");
break;
}
else {
for (i = 0;i<3;i++) {
if (FD_ISSET(pps[i][0], &read_set)) {
int rc = read(pipes[i][0], buffer, 100);
if (rc > 0) {
printf("%s\n",buffer);
memset(buffer, 0, 100);
}
}
}
}
答案 0 :(得分:1)
来自v.size()-1
select()
请注意以下声明:
“返回三个返回的描述符集中包含的文件描述符的数量”
(与手册页的其余部分一起)说
因此,要返回零,任何关联的fd都不能输入任何数据,并且不会发生I / O错误。
那么为什么0代码中的RETURN VALUE
On success, select() and pselect() return the number of file descrip‐
tors contained in the three returned descriptor sets (that is, the
total number of bits that are set in readfds, writefds, exceptfds)
which may be zero if the timeout expires before anything interesting
happens. On error, -1 is returned, and errno is set appropriately; the
sets and timeout become undefined, so do not rely on their contents
after an error.
永远不会返回?
答案:因为只有在发生超时并且发布的代码永远不会设置超时时才会返回0。