2

新的一天,新的问题。不知何故,我发现自己几乎每天都在这里问问题,顺便说一句。感谢您迄今为止的支持。我实现了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从所有套接字读取...?

4

1 回答 1

3

select()改变你的read_fds

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

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

于 2012-05-24T08:54:01.853 回答