C / select只从一个文件描述符中读取

时间:2012-05-24 08:46:45

标签: c sockets

新的一天,新的问题。不知何故,我发现自己几乎每天都在这里提问,顺便说一句。感谢您的支持到目前为止。我实现了select来读取四个文件描述符,但它只从一个读取。

我有一个测试应用程序将所有四个端口上的数据包发送到运行C程序的第二台机器上:

data_packet to port[13501]
data_packet to port[13502]
data_packet to port[13503]
data_packet to port[13504]
data_packet to port[13501]

依旧......

使用tcpdump我可以看到,测试应用程序运行正常:

08:02:26.391843 IP 10.1.1.2.2000 > 10.1.1.40.13501: UDP, length: 28
08:02:27.391794 IP 10.1.1.2.2000 > 10.1.1.40.13502: UDP, length: 28
08:02:28.391820 IP 10.1.1.2.2000 > 10.1.1.40.13503: UDP, length: 28
08:02:29.391918 IP 10.1.1.2.2000 > 10.1.1.40.13504: UDP, length: 28

但我的应用程序只是从一个FD(套接字)读取,在开始时我在fd_set中显示所有可用的文件描述符:

thread 1 started, pc_packet_receiver 
thread 2 started, pc_packet_sender 
sock_fd[9]
sock_fd[10]
sock_fd[11]
sock_fd[12]

received on sock_fd[12] on ETH0 on port 13503
received on sock_fd[12] on ETH0 on port 13503
received on sock_fd[12] on ETH0 on port 13503
received on sock_fd[12] on ETH0 on port 13503
[ctrlC] sockets closed, threads stopped...

围绕select的实施如下所示:

    FD_SET(sock_fd[i], &read_fds);
    fdmax = sock_fd[i];
}

for(i = 0; i < 4; i++) {
    printf("sock_fd[%d]\n",sock_fd[i]);
}

while(keepRunning) {

    bzero(&incoming_msg, MAX_PAYLOAD_LEN);
    bzero(&outgoing_msg, MAX_PAYLOAD_LEN);
    bzero(&peer, peer_len);

    readsocks = select(fdmax+1, &read_fds, NULL, NULL, NULL);

    if (readsocks < 0) {
        perror("select");
        exit(EXIT_FAILURE);
    } else if (readsocks == 0) {
        printf("nothing to read from\n");
        continue;
    }

    for(i = 0; i < 4; i++) {

        if(FD_ISSET(sock_fd[i], &read_fds)) {

            in_msg_len = recvfrom(sock_fd[i],
                incoming_msg,
                MAX_PAYLOAD_LEN,
                0,
                (struct sockaddr *) &client_addr,
                &sock_len_client);

            if (in_msg_len < 0) {
                perror("failed to receive data\n");
                exit(EXIT_FAILURE);
            }

            strncpy(outgoing_msg, incoming_msg, in_msg_len);

            if(getsockname(sock_fd[i], &peer, &peer_len) < 0) {
                perror("getsockname() failed");
                return (-1);
            }

            receiving_eth_port = (int)ntohs(peer.sin_port);

#if DBG_OUTPUT
            printf("received on sock_fd[%d] on ETH0 on port %d\n",   sock_fd[i], receiving_eth_port);
#endif

如何从所有套接字中读取select ...?

1 个答案:

答案 0 :(得分:2)

select()改变了您的read_fds

第一次调用select()后,read_fds可能只设置了一个fd位,因此您只检查所有剩余循环中的此文件描述符。

解决方案是每次调用read_fds之前重新构建select()。这可能听起来很乏味,但在处理select()时这是常见的做法。