新的一天, 新的问题。 我发现我几乎每天都在这里问问题, Btw. 感谢你们迄今为止的支持。 我从四个文件描述符中应用了 < code> 选择 < / code > 来阅读, 但是它只读一个 。
我有一个测试应用程序 在所有四个港口 发送包到第二台机器, 在那里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 (Socket), 一开始我展示了 < code> fd_ set code > 内所有可用的文件描述符 :
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]
",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
");
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
");
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
", sock_fd[i], receiving_eth_port);
#endif
我如何才能实现 select
在所有插座上读到的 select
?