您的位置:首页 > 其它

select的fd超过1024将会非常危险------FD_SET导致core dump

2017-06-25 15:20 253 查看
         关于linux select无须多说, 来看代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/time.h>
#include<sys/types.h>

int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("para error\n");
return -1;
}

struct timeval tv; // 超时时间
tv.tv_sec = 10;
tv.tv_usec = 500; // 注意单位是微秒

fd_set rdfds;
FD_ZERO(&rdfds); // 描述集初始化

unsigned int n = atoi(argv[1]);
printf("n is %u\n", n);
for(unsigned int i = 0; i < n; i++)
{
FD_SET(i, &rdfds);
}

printf("to select\n");
select(n, &rdfds, NULL, NULL, &tv);

return 0;
}       执行结果:
xxxxxx:~/network> g++ -g server.cpp
server.cpp:34:2: warning: no newline at end of file
xxxxxx:~/network> ./a.out 2000
n is 2000
Segmentation fault (core dumped)
xxxxxx:~/network> gdb a.out core
GNU gdb 6.6
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i586-suse-linux"...
Using host libthread_db library "/lib/libthread_db.so.1".

warning: Can't read pathname for load map: Input/output error.
Reading symbols from /lib/libonion.so...done.
Loaded symbols for /lib/libonion.so
Reading symbols from /usr/lib/libstdc++.so.6...done.
Loaded symbols for /usr/lib/libstdc++.so.6
Reading symbols from /lib/libm.so.6...done.
Loaded symbols for /lib/libm.so.6
Reading symbols from /lib/libgcc_s.so.1...done.
Loaded symbols for /lib/libgcc_s.so.1
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/libdl.so.2...done.
Loaded symbols for /lib/libdl.so.2
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `
Program terminated with signal 11, Segmentation fault.
#0 0x080485af in main (argc=-1, argv=0xffffffff) at server.cpp:27
27 FD_SET(i, &rdfds);
(gdb)         可见, 程序core在FD_SET处, 为什么呢, 看看linux源码中关于FD_SET的部分吧:
static __inline__ void __FD_SET(unsigned long fd, __kernel_fd_set *fdsetp)
{
unsigned long _tmp = fd / __NFDBITS;
unsigned long _rem = fd % __NFDBITS;
fdsetp->fds_bits[_tmp] |= (1UL<<_rem);
}

#define __NFDBITS (8 * sizeof(unsigned long))

typedef struct {
unsigned long fds_bits [__FDSET_LONGS];
} __kernel_fd_set;

#define __FDSET_LONGS (__FD_SETSIZE/__NFDBITS)

#define __FD_SETSIZE 1024

        一幕撩人, 一目了然。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: