我只是想测试一个关于在 Linux(Ubuntu 13.04/Debian 6)上选择监听超过 1024 个文件描述符的错误。我覆盖了 FD_SETSIZE 和 __FD_SETSIZE 宏。
然后,在程序结束时关闭文件描述符时,perror() 报告有一些错误。在我的 PC 上如下所示:(错误的数量取决于收听的数量)。
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;
}
在编译时会出现一些关于重新定义 Marcos 的警告。