Skip to content

Instantly share code, notes, and snippets.

@luchenqun
Last active December 14, 2017 09:15
Show Gist options
  • Save luchenqun/7d1f28ca2f8231d166a30ad234234e48 to your computer and use it in GitHub Desktop.
Save luchenqun/7d1f28ca2f8231d166a30ad234234e48 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <stdlib.h>
#define __NFDBITS (8 * sizeof(unsigned long)) //每个ulong型可以表示多少个bit,
#define __FD_SETSIZE 1024 //socket最大取值为1024
#define __FDSET_LONGS (__FD_SETSIZE/__NFDBITS) //bitmap一共有1024个bit,共需要多少个ulong
typedef struct {
unsigned long fds_bits [__FDSET_LONGS]; //用ulong数组来表示bitmap
} __kernel_fd_set;
typedef __kernel_fd_set fd_set;
//每个ulong为32位,可以表示32个bit。
//fd >> 5 即 fd / 32,找到对应的ulong下标i;fd & 31 即fd % 32,找到在ulong[i]内部的位置
#define __FD_SET(fd, fdsetp) (((fd_set *)(fdsetp))->fds_bits[(fd) >> 5] |= (1<<((fd) & 31))) //设置对应的bit
#define __FD_CLR(fd, fdsetp) (((fd_set *)(fdsetp))->fds_bits[(fd) >> 5] &= ~(1<<((fd) & 31))) //清除对应的bit
#define __FD_ISSET(fd, fdsetp) ((((fd_set *)(fdsetp))->fds_bits[(fd) >> 5] & (1<<((fd) & 31))) != 0) //判断对应的bit是否为1
#define __FD_ZERO(fdsetp) (memset (fdsetp, 0, sizeof (*(fd_set *)(fdsetp)))) //memset bitmap
int main(int argc ,char **argv)
{
fd_set allset;
cout << sizeof(allset.fds_bits[0]) << endl;
FD_ZERO(&allset);
for(int fd=0; fd<=10; fd++){
FD_SET(fd, &allset);
cout << fd << ":";
for(int i=0; i<16;i++){
printf("%llu ", allset.fds_bits[i]);
}
cout << endl;
}
return 0;
}
//8
//0:1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//1:3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//2:7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//3:15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//4:31 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//5:63 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//6:127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//7:255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//8:511 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//9:1023 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
//10:2047 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment