我的操作系统是64位的Centos6.4。我有一个关于如何 fd_set 管理 FD_SET 添加 fd 的问题。代码如下:
fd_set my_set;
FD_SET(31, &my_set);
然后,我显示 my_set.fds_bits[...]。my_set.fds_bits[0] 等于 0x0000000080000000,my_set.fds_bits[1~...] 为零。我可以理解结果。但我也写个案例,代码如下:
fd_set my_set;
FD_SET(63, &my_set);
我显示my_set.fds_bits[...]。my_set.fds_bits[0]等于0x0。在我看来,结果应该是my_set.fds_bits[0]等于0x8000000000000000。我真的不理解为什么第二个结果是 0x0。等于 63 的 fd 在 my_set 中没有状态。
完整的测试代码如下:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <pthread.h>
#define BUFSIZE 1024
void printFDSET(fd_set target_sets)
{
int uIndex = 0;
int model_num = __NFDBITS;
for(uIndex = 0; uIndex < 10/*FD_SETSIZE/model_num*/; uIndex++)
{
printf("0x%016x\t", target_sets.fds_bits[uIndex]);
if(uIndex % 4 == 3)
printf("\n");
}
printf("\n");
return;
}
int main(int argc, char* argv[])
{
fd_set my_set;
FD_ZERO(&my_set);
printf("sizeof(long int) = %d\n", sizeof(long int));
printf("FD_SETSIZE = %d\n", FD_SETSIZE);
printf("size = %zu\n", sizeof __FDS_BITS(&my_set)[0]);
printf("\n\n");
int unfd = 31;
FD_SET(unfd, &my_set);
printf("%d is added to my_set:\n", unfd);
printFDSET(my_set);
printf("\n\n");
FD_CLR(unfd, &my_set);
unfd = 63;
printf("%d is added to my_set:\n", unfd);
FD_SET(unfd, &my_set);
printFDSET(my_set);
return 0;
}
最佳答案
Doesn't fd that is equal to 63 have a state in my_set.
它有。您只是没有正确打印值,因为您忘记了 printf
格式字符串中的长度修饰符 l
。
printf("0x%016lx\t", __FDS_BITS(&target_sets)[uIndex]);
关于c - 关于linux中的FD_SET和fd_set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39124814/