我只是想测试一下在Linux上选择侦听超过1024个文件描述符的错误(Ubuntu 13.04 / Debian 6)。 我重写了FD_SETSIZE和__FD_SETSIZE宏。
然后,perror()报告在程序结束时关闭文件描述符时会出现一些错误。在我的电脑上如下:(错误的数量取决于侦听的数量)。
closing file at 0
close: Bad file descriptor
closing file at 1
close: Bad file descriptor
closing file at 2
close: Bad file descriptor
closing file at 3
close: Bad file descriptor
closing file at 4
close: Bad file descriptor
closing file at 5
close: Bad file descriptor
closing file at 6
close: Bad file descriptor
closing file at 7
close: Bad file descriptor
守则如下:
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#define __FD_SETSIZE 8192
#define FD_SETSIZE 8192
#define NR_SELECT 2048
char filename[10];
void init()
{
struct rlimit* rlim;
int n;
rlim = (struct rlimit*)malloc(sizeof(struct rlimit));
n=getrlimit(RLIMIT_NOFILE,rlim);
if (n == -1) {
perror("getrlimit");
exit(1);
}
rlim->rlim_max=8192;
rlim->rlim_cur=8192;
n=setrlimit(RLIMIT_NOFILE,rlim);
if (n == -1) {
perror("setrlimit");
exit(1);
}
}
int main(void)
{
int fd[4096];
int i;
fd_set fdset;
struct timeval tv;
int retval;
init();
/*clear and init a fd set*/
FD_ZERO(&fdset);
for (i=0;i<NR_SELECT;i++) {
sprintf(filename,"./tst%d",i);
fd[i]=open(filename,O_CREAT|O_RDWR,0666);
if (fd[i] == -1) {
fprintf(stderr,"opening at %dfile \n",i);
perror("open while opening at \n");
exit(1);
}
}
for (i=0;i<NR_SELECT;i++) {
FD_SET(fd[i],&fdset);
if (!FD_ISSET(fd[i],&fdset)) {
fprintf(stderr,"checking fd[%d] in fdset",i);
perror("FD_ISSET");
exit(1);
}
}
tv.tv_sec=5;
tv.tv_usec=0;
retval = select(4096,&fdset,NULL,NULL,&tv);
if (retval == -1)
perror("select()");
else if (retval) {
printf("data available\n");
}
for (i=0;i<NR_SELECT;i++) {
int n;
n = close(fd[i]);
if (n== -1) {
fprintf(stderr,"closing file at %d\n",i);
perror("close");
}
}
return 0;
}
虽然编译会对重新定义马科斯有一些警告。
答案 0 :(得分:0)
您需要先定义FD_SETSIZE
,然后再添加系统上的标题sys/select.h
。否则该标题将定义它,您的重新定义将不执行任何操作或破坏FD_ *宏。
另外。不要使用select
。使用poll
,epoll
,kqueue
或任何其他旨在更好地处理20多个文件描述符的现代界面。