study_20160808 study_20160808 - 3 months ago 12
Linux Question

About FD_SET and fd_set in linux

My os is 64bits Centos6.4. I have a question about how to fd_set manage FD_SET add the fd.Follow code is case:

fd_set my_set;
FD_SET(31, &my_set);


Then, I show my_set.fds_bits[...].The my_set.fds_bits[0] is equal to 0x0000000080000000, my_set.fds_bits[1~...] is zero.I can understand the result.But I also write an case,Follow code:

fd_set my_set;
FD_SET(63, &my_set);


I show my_set.fds_bits[...].The my_set.fds_bits[0] is equal to 0x0.In my opinion, the result should be my_set.fds_bits[0] is equal to 0x8000000000000000.I really don't understand why sencond result is 0x0. Doesn't fd that is equal to 63 have a state in my_set.

Here is full testing code:

#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;
}

Answer

Doesn't fd that is equal to 63 have a state in my_set.

It has. You just didn't correctly print the value, because you forgot the length modifier l in the printf format string.

        printf("0x%016lx\t", __FDS_BITS(&target_sets)[uIndex]);
Comments