如何只读取已更改的文件描述符

时间:2013-10-20 06:14:58

标签: c sockets

当select返回filw描述符已更改时,我如何只读取哪些套接字有数据?当FD改变时,ATM执行,即使该FD在缓冲区中没有数据,也执行printf语句。

编辑:我正在阅读的问题是继续阅读虽然我没有发送任何数据。我使用1个插槽来发送接收。

void receive(struct nodeData *nd, struct sockInfo *si){
char buffer[MAXBUF];
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
// ----Wait in select until file descriptors change----
int y = select(si->maxFD, &si->fd_read_set, NULL, NULL, &timeout);

if (y <= 0)
    return;
for (int i=0; i < nd->netTopo->n; i++) {
    /* ----Was it child i---- */
    if (FD_ISSET(si->mastFD[i], &si->fd_read_set)) {
        read(si->mastFD[i], buffer, MAXBUF);
        printf("%d %d %d \n",buffer[0], buffer[1], buffer[2]);
    }
}
}

1 个答案:

答案 0 :(得分:1)

if (read(si->mastFD[i], buffer, MAXBUF) > 0)
        printf("%d %d %d \n",buffer[0], buffer[1], buffer[2]); 

这将打印垃圾3/4的时间。它应该是:

int count = read(si->mastFD[i], buffer, MAXBUF);
if (count >= 3)
    printf("%d %d %d \n",buffer[0], buffer[1], buffer[2]); 
else if (count == 2)
    printf("%d %d \n",buffer[0], buffer[1]); 
else if (count == 1)
    printf("%d \n",buffer[0]); 
else if (count == 0)
{
    printf("EOS on %d \n",si->mastFD[i]); 
    close(si->mastFD[i]);
}
else if (count < 0)
{
    printf("error on %d: %s \n",si->mastFD[i], strerr[errno]); 
    close(si->mastFD[i]);
}