[英]linux C select() never return 0
我對選擇和管道有疑問。 我正在嘗試創建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);
}
}
}
}
從select()
的手冊頁中
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.
請注意以下語句:
“返回三個返回的描述符集中包含的文件描述符的數量”
其中(以及手冊頁的其余部分)說
因此,要返回零,則任何關聯的fd都不能輸入任何數據,並且不會發生I / O錯誤。
那么,為什么代碼中的select()
從不返回0?
答案:因為只有在發生超時並且發布的代碼永遠不會設置超時時才返回0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.